我正在尝试根据字符串字段用户名从单个表中检索整数值。我已经尝试过使用存储过程和直接文本。当我执行存储过程时,我得到了正确的返回值;然而,正确的结果并没有出现。
这是两组代码 - 直接文本 -
public int GetUserRole(string CUSER)
{
try
{
SQLCON = new SqlConnection(connectionString);
SQLCON.Open();
SQLCommand = new SqlCommand();
SQLCommand.CommandType = CommandType.Text;
SQLCommand.Parameters.Add("USUsername", SqlDbType.VarChar).Value = CUSER;
SQLCommand.CommandText = "SELECT USRole FROM tblUser WHERE USUsername = CUSER";
Int32 USRole = (Int32) SQLCommand.ExecuteScalar();
return USRole;
}
catch
{
HttpContext.Current.Response.Redirect("~/ErrorRedirect.aspx", false);
return 0;
}
}
SQL查询:
ALTER PROCEDURE [dbo].[spGetUserRole]
-- Add the parameters for the stored procedure here
@username VARCHAR(50)
AS
BEGIN
-- Declare the return variable here
DECLARE @USRole as int
-- Add the T-SQL statements to compute the return value here
SELECT @USRole = tblUser.USRole FROM tblUser WHERE USUsername = @username
-- Return the result of the function
RETURN @USRole
END