2012-09-12 132 views
0

我写了一个sql函数,它返回一个标量:1如果密码正确,否则为0。具有两个参数的sql函数。从VB .NET调用

CREATE FUNCTION check_credential( @User_IN nvarchar(50), @Pwd_IN nvarchar(50)) 
    RETURNS int 
    AS 
    BEGIN 
    DECLARE @PwdRES int 
    DECLARE @PWD_DB varbinary(255) 

    IF (@User_IN is not null and @User_IN != '' and @Pwd_IN is not null and @Pwd_IN != '') 
begin 
    SELECT @PWD_DB = password FROM myTable WHERE username = @User_IN 
    SET @PwdRES = pwdcompare(@Pwd_IN, @PWD_DB) 
end 
ELSE 
    SET @PwdRES = 0 

    RETURN @PwdRES 
    END 

而且这个工作正常。

我使用下面的代码调用SQL函数:

Dim conn As SqlConnection 
    Dim sqlcmd As SqlCommand 
    Dim da As SqlClient.SqlDataAdapter 
    Dim table As DataTable 
    Dim Result As Integer 

    conn = New SqlConnection(ConnectionString) 

    sqlcmd = New SqlClient.SqlCommand() 
    sqlcmd.Connection = conn 
    conn.Open() 

    sqlcmd.CommandType = CommandType.StoredProcedure 
    sqlcmd.CommandText = "check_credential" 

    sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@username", Utilities.NothingToDBNull(user))) 
    sqlcmd.Parameters.Add(New SqlClient.SqlParameter("@password", Utilities.NothingToDBNull(password))) 

在这一点上,我想执行SQLCMD并获得返回值。

回答

3

一个function是一个stored procedure

要么转换你的函数存储过程或更改命令

"select dbo.check_credential(@username, @password)" 

将CommandType设置为Text,并使用不同ExecuteScalar

Result = Convert.ToInt32(cmd.ExecuteScalar()) 
+0

是不是可以使用的功能? – GVillani82

+1

@ Joseph82在存储过程中包装函数。 –

+0

@ Joseph82为什么它是一个功能这么重要? – podiluska

0

在这种情况下,您需要定义一个output参数。

在SQL函数:

@Value int output, // Define it in the Parameters 

在这个参数让你的计算值说

@value = 0 
在C#代码

现在:

SqlParameter user = cmd.Parameters.Add("@value", SqlDbType.int); 
user.Direction = ParameterDirection.Output; 

在这里,您可以检查是否用户是0或1

1

使@PwdRES为output参数。还声明参数为你的代码输出,然后将包含来自函数的返回值,一旦命令被执行:

sqlcmd.Parameters.Add("@PwdRES ", SqlDbType.Int) 
sqlcmd.Parameters("@PwdRES ").Direction = ParameterDirection.Output) 

你需要你的函数转换成一个存储过程(或添加存储调用该函数的过程)来让它工作我认为。

+0

ok。我怎样才能调用函数并在哪里可以找到结果? – GVillani82

+0

查看此线程中的示例:http://social.msdn.microsoft.com/Forums/sv/adodotnetdataproviders/thread/ed8c53cf-9bbd-43e2-81ef-0d5c8b5ed3ff – Simon

相关问题