读取c#中sql server存储过程的返回值?

kcwpcxri  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(355)

我想捕捉从c#中的sql server存储过程返回的-1、0、1值。
sql服务器:

  1. IF EXISTS(SELECT * FROM _Users WHERE UserName = @UserName AND [Password] != @Password)
  2. BEGIN
  3. RETURN -1
  4. END
  5. IF EXISTS(SELECT * FROM _Users WHERE UserName != @UserName AND [Password] != @Password)
  6. BEGIN
  7. RETURN 0
  8. END
  9. IF EXISTS(SELECT * FROM _Users WHERE UserName = @UserName AND [Password]= @Password)
  10. BEGIN
  11. RETURN 1
  12. END

c级#
我们能改变下面代码的返回值吗?只要按我所希望的做就行了?

  1. public User getUser(string name, string password)
  2. {
  3. User user = null;
  4. using (var connection = Database.GetConnection())
  5. {
  6. var command = new SqlCommand("SP_GetUser @UserName, @Password", connection);
  7. command.Parameters.Add(new SqlParameter("UserName", name));
  8. command.Parameters.Add(new SqlParameter("Password", password));
  9. connection.Open();
  10. using (var reader = command.ExecuteReader())
  11. {
  12. while (reader.Read())
  13. {
  14. user = new User();
  15. user.UserId = Convert.ToInt32(reader["UserId"]);
  16. user.userName = Convert.ToString(reader["UserName"]);
  17. user.password = Convert.ToString(reader["Password"]);
  18. }
  19. }
  20. connection.Close();
  21. }
  22. return user; // I want to return -1, 0, 1
  23. }

6jygbczu

6jygbczu1#

  1. SqlParameter returnValueParam = new SqlParameter() { Direction = ParameterDirection.ReturnValue };
  2. command.Parameters.Add(returnValueParam);
  3. // Read everything from your DataReader before trying to obtain the return value
  4. // In fact after you close the connection
  5. var returnValue = returnValueParam.Value;

笔记:
确保您设置了 command.CommandType = CommandType.StoredProcedure; (并从 CommandText 因为它在使用时只能是sp名称 CommandType.StoredProcedure ).
创建数据时,应始终指定数据类型和比例/精度(如果相关) SqlParameter 因为可能会有意外的副作用,允许自动设置数据类型。最好的做法是完整地命名参数,包括 @ ,所以

  1. new SqlParameter("UserName", name);

应该是真的

  1. // Where the type and length match your SP
  2. new SqlParameter("@UserName", SqlDbType.NVarChar, 128) { Value = name };

从技术上讲,存储过程的返回值是存储过程的“执行状态”。你通常会使用 OUTPUT 参数返回用户数据。然而,在我看来,你的用例是一样的好。
正如@marc_s所指出的:你不应该使用 sp_ 存储过程的前缀。microsoft已经保留了这个前缀供自己使用(请参见命名存储过程),并且您确实会在将来的某个时候遇到名称冲突的风险。这对存储过程的性能也不利。最好只是避免 sp_ 使用其他的前缀-或者根本不使用前缀!

展开查看全部

相关问题