用C#调用SQL函数

时间:2015-03-05 14:53:57

标签: c# sql asp.net sql-server

我在SQL中编写这个函数:

   ALTER FUNCTION Fn_CheckBill
(
@image AS image,
@number AS nvarchar(50),
@date AS nchar(10)
)
RETURNS bit
AS
BEGIN
DECLARE @flag bit;
IF EXISTS ( SELECT * 
            FROM tblBill 
            WHERE ((cast([Image] as varbinary(max)) = cast(@image as varbinary(max))) AND (Number = @number) AND ([Date] = @date)) )
            BEGIN
                SET @flag = 0
            END
ELSE
    BEGIN
        SET @flag = 1
    END

RETURN @flag
END

并在我的C#源代码中编写此代码:

int flag;
    try
    {
        objCommand = new SqlCommand("SELECT Fn_CheckBill(@image,@date,@number) AS int");
        objCommand.CommandType = CommandType.Text;

        objCommand.Parameters.AddWithValue("image", image);
        objCommand.Parameters.AddWithValue("number", number);
        objCommand.Parameters.AddWithValue("date", _Date);

        using (objConnection = new SqlConnection(connenctString))
        {

            objConnection.Open();
            objCommand.Connection = objConnection;
            flag = int.Parse(objCommand.ExecuteScalar().ToString());
        }

        if (flag == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch
    {
        return false;
    }

但它在执行时抛出此异常: 'Fn_CheckBill'不是可识别的函数名称。

请帮我解决这个问题:(

2 个答案:

答案 0 :(得分:3)

您需要在任何SQL函数调用中提供架构

objCommand = new SqlCommand("SELECT dbo.Fn_CheckBill(@image,@date,@number) AS int");

答案 1 :(得分:0)

我会考虑将其重写为内联表值函数。像这样:

create FUNCTION Fn_CheckBill
(
    @image AS varbinary(max),
    @number AS nvarchar(50),
    @date AS nchar(10)
)
RETURNS table
AS
RETURN
    SELECT CAST(count(*) as bit) as RowFound
    FROM tblBill 
    WHERE [Image] = @image
        AND Number = @number
        AND [Date] = @date