Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

c# - Command.ExecuteScalar always return null while Stored Procedure in Management Studio runs fine

I have the following SQL stored procedure with one input parameter and one out parameter.

CREATE PROCEDURE [dbo].[spCanUserEdit]
(
@username nvarchar(255)
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CanEdit bit

SELECT
    @CanEdit = CanUserEdit
FROM tblUsers
WHERE username = LOWER(@username)
RETURN SELECT @CanEdit
END
GO

In the stored procedure above CanUserEdit column in tblUsers is bit type column and with default value to 0. Now when I execute this procedure in Management Studio it runs fine but when i use command.ExecuteScalar() in my C# code, it always returns null. Could anyone please tell me what I am doing wrong here.

Following is my C# method

public static bool CanUserEdit(string userName)
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[Constants.ConnectionStringName].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "spCanUserEdit";
            cmd.Connection = conn;

            cmd.Parameters.Add(new SqlParameter("@username", userName));

            conn.Open();
            bool canEdit = (bool)cmd.ExecuteScalar();

            return canEdit;
        }
    }
}

Kind Regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is in the way you return data. If you want to use ExecuteScalar, you should not RETURN but instead simply SELECT.

Try to change the SP as following:

CREATE PROCEDURE [dbo].[spCanUserEdit]
(
 @username nvarchar(255)
)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @CanEdit bit

SELECT
    @CanEdit = CanUserEdit
FROM tblUsers
WHERE username = LOWER(@username)

SELECT @CanEdit

RETURN 0
END
GO

If you can't change the SP, but the code, the solution is to read parameter '@ReturnValue' with ExecuteNonQuery.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...