Calling SQL Functions directly from C#

后端 未结 6 762
遇见更好的自我
遇见更好的自我 2021-02-08 12:49

I have a requirement to run a query against a database that will return either a zero or one (Checking for existance of specific criteria). The Tech specs I\'ve been given for r

6条回答
  •  一整个雨季
    2021-02-08 13:16

    i use this sql scalar function

    CREATE FUNCTION DAYSADDNOWK(@addDate AS DATE, @numDays AS INT)
    RETURNS DATETIME
    AS
    BEGIN
        SET @addDate = DATEADD(d, @numDays, @addDate)
        IF DATENAME(DW, @addDate) = 'sunday'   SET @addDate = DATEADD(d, 1, @addDate)
        IF DATENAME(DW, @addDate) = 'saturday' SET @addDate = DATEADD(d, 2, @addDate)
    
        RETURN CAST(@addDate AS DATETIME)
    END
    GO
    

    then this is my c# code

    using (SqlCommand cmd3 = new SqlCommand("SELECT dbo.DAYSADDNOWK", ClassV.con))
                        ClassV.con.Open();
                        SqlCommand brecord = ClassV.con.CreateCommand();
                        brecord.CommandText = "INSERT INTO TblBorrowRecords VALUES ('" + DGStudents.CurrentRow.Cells[1].Value.ToString() + "','" + DGStudents.CurrentRow.Cells[2].Value.ToString() + "','" + DGStudents.CurrentRow.Cells[4].Value.ToString() + "','" + DGStudents.CurrentRow.Cells[3].Value.ToString() + "','" + DG.CurrentRow.Cells[4].Value.ToString() + "','" + DG.CurrentRow.Cells[5].Value.ToString() + "','" + DG.CurrentRow.Cells[6].Value.ToString() + "','" +System.DateTime.Now.Date.ToShortDateString() + "' , dbo.DAYSADDNOWK(GETDATE(),5) ,null , '" + ClassV.lname.ToString() + ", " + ClassV.fname.ToString() + " " + ClassV.mname.ToString() + "', null, 'Good',null)";
                        var DAYSADDNOWK = brecord.ExecuteScalar();
    

    my C# code skips the function

提交回复
热议问题