SQL存储过程比较NVARCHAR无法按预期工作

时间:2014-06-17 13:06:22

标签: c# sql-server stored-procedures sql-server-2012-express

我有以下SQL Server 2012 Express存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Andy Armstrong
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE db_CheckLogin 
    -- Add the parameters for the stored procedure here
    @LoginName NVARCHAR(15),
    @Password NVARCHAR(15),
    @ReturnCode UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT UserID=@ReturnCode FROM tblMemberLogin WHERE LoginName = @LoginName AND LoginPassword = @Password;
END
GO

我从.NET C#存储过程调用它,如下所示:

// Create Command Interface
            SqlCommand cmdStoredProc = new SqlCommand("db_CheckLogin", objConnection);
            cmdStoredProc.CommandType = CommandType.StoredProcedure;
            // Fill The Parameters Collection Based Upon Stored Procedure.
            SqlParameter workParam = null;
            workParam = cmdStoredProc.Parameters.Add("@LoginName", SqlDbType.NVarChar, 15);
            workParam = cmdStoredProc.Parameters.Add("@Password", SqlDbType.NVarChar, 15);
            // Prepare Output Parameter
            workParam = cmdStoredProc.Parameters.Add("@ReturnCode", SqlDbType.UniqueIdentifier);
            workParam.Direction = ParameterDirection.Output;
            // Set Values For Our Procedure
            cmdStoredProc.Parameters["@LoginName"].Value = ctrlUsername.Text;
            cmdStoredProc.Parameters["@Password"].Value = ctrlPassword.Text;
            // Exec Procedure
            cmdStoredProc.ExecuteNonQuery();

但由于某种原因,它没有返回我期望的行。

tblMemberLogin的架构如下:

UserID = uniqueidentifier pk, LoginName = NVARCHAR(15) LoginPassword = NVARCHAR(15)

我在该表格中有一行,其用户名为myUser,密码为passw0rd

但是运行代码返回0行。手动运行存储过程也不起作用 - 运行如下的查询:

SELECT UserID FROM tblMemberLogin WHERE LoginName =&#39; myUser&#39; AND LoginPassword =&#39; passw0rd&#39;完美运作!请帮我看看我哪里出错。

1 个答案:

答案 0 :(得分:4)

它应该如下所示: -

SELECT @ReturnCode =UserID FROM tblMemberLogin WHERE LoginName = @LoginName AND LoginPassword = @Password;