在C#中仅获取输出参数中的第一个字符

问题描述 投票:2回答:4

我已经定义了输出参数,如下所示:

C#:

scom.Parameters.Add("@User_ID",SqlDbType.VarChar,8).Direction = ParameterDirection.Output ;

SQL:

@User_ID varchar(8) output

我在Sql Server中执行过程时获取完整的字符串,但只获取C#中的第一个字符。我搜索了很多,并确保在C#和Sql中定义了大小。即使我尝试使用固定长度字符(Char(8)),但仍然只获得C#中的第一个字符。请告诉我这是什么问题。

C#代码:

public bool CheckPhone(string phoneNumber)
{
    SqlConnection myconn=new SqlConnection(connectionString);
    try
    {
        myconn.Open();
        SqlCommand scom = new SqlCommand("AuthenticatePhone", myconn);
        scom.CommandType = CommandType.StoredProcedure;
        scom.Parameters.Add("@phoneNumber", SqlDbType.BigInt).Value = Convert.ToInt64(phoneNumber);
        scom.Parameters.Add("@User_ID", SqlDbType.Char, 8).Direction = ParameterDirection.Output;

        scom.Parameters.Add("@User_Name", SqlDbType.Char, 120).Direction = ParameterDirection.Output;

        scom.ExecuteNonQuery();
        if (scom.Parameters["@User_Name"] == null)
        {
            return false;
        }
        else
        {
            UserID = (string)scom.Parameters["@User_ID"].Value;//.ToString();
            UserName = (string)scom.Parameters["@User_Name"].Value;//.ToString();
            myconn.Close();
            return true;
        }
    }
    catch (Exception e)
    { 
        string error = e.InnerException + e.Message; 
    }
    finally 
    { 
        myconn.Close();
    }

    return false;
}

SQL:

Create procedure dbo.AuthenticatePhone

  @phoneNumber numeric(11,0)        ,
  @User_ID     varchar(8)    output ,
  @User_Name   varchar(120)  output
as
begin

  Select @User_ID   = convert(varchar(8),[User_ID]) ,
         @User_Name = [User_Name]
  from dbo.NRE_Users
  where PhoneNumber = @phoneNumber
  ;

  print @User_ID
  print @User_Name

end
c# sql-server parameters output
4个回答
1
投票

不责备我。鉴于此存储过程:

create procedure dbo.AuthenticatePhone

  @phoneNumber numeric(11,0)        ,
  @User_ID     varchar(8)    output ,
  @User_Name   varchar(120)  output

as

  set @User_ID   = '1234567890' -- should be truncated to '12345678'
  set @User_Name = 'The quick brown fox jumped over the lazy dog.'

  return 0
go

在SSMS中运行此SQL:

 declare @userId   varchar(1000) = 'xxx'
 declare @userName varchar(1000) = 'yyy'
 exec AuthenticatePhone 1 , @User_ID = @userId out , @User_Name = @userName out
 select @userId,@userName

得到预期的结果:

  • @userId包含预期的12345678
  • @userName包含预期的The quick brown fox jumped over the lazy dog.

通过C#执行:

using ( SqlConnection connection = new SqlConnection( "Server=localhost;Database=sandbox;Trusted_Connection=True;" ) )
using ( SqlCommand    command    = connection.CreateCommand() )
{

  command.CommandType = CommandType.StoredProcedure;
  command.CommandText = "dbo.AuthenticatePhone" ;

  SqlParameter phoneNumber = new SqlParameter {
    ParameterName = "@phoneNumber"           ,
    IsNullable    = true                     ,
    Direction     = ParameterDirection.Input ,
    Value         = 2125551212L              ,
    } ;
  command.Parameters.Add( phoneNumber ) ;

  SqlParameter userId = new SqlParameter {
    ParameterName = "@User_ID"                ,
    IsNullable    = true                      ,
    Direction     = ParameterDirection.Output ,
    DbType        = DbType.String             ,
    Size          = 1000                      ,
    Value         = DBNull.Value              ,
    } ;
  command.Parameters.Add( userId ) ;

  SqlParameter userName = new SqlParameter {
    ParameterName = "@User_Name" ,
    IsNullable    = true ,
    Direction     = ParameterDirection.Output ,
    DbType        = DbType.String ,
    Size          = 1000 ,
    Value         = DBNull.Value ,
    } ;
  command.Parameters.Add( userName ) ;

  connection.Open() ;
  int rowsAffected = command.ExecuteNonQuery() ;
  connection.Close() ;

  Console.WriteLine( "Rows Affected: {0}"     , rowsAffected             ) ;
  Console.WriteLine( "User ID:       {{{0}}}" , userId.Value   as string ) ;
  Console.WriteLine( "User Name:     {{{0}}}" , userName.Value as string ) ;

}

同样导致预期

Rows Affected: -1
User ID:       {12345678}
User Name:     {The quick brown fox jumped over the lazy dog.}

甚至替换你的参数定义:

command.Parameters.Add("@phoneNumber", SqlDbType.BigInt).Value = 2125551212L ;
command.Parameters.Add("@User_ID", SqlDbType.Char, 8).Direction = ParameterDirection.Output;
command.Parameters.Add("@User_Name", SqlDbType.Char, 120).Direction = ParameterDirection.Output;

你得到了预期的结果。

虽然你可能会注意到SqlDbType.Char是一个SQL char(X)。它相当于T-SQL中的`convert(char(120),'John Doe')。 .Net字符串将填充空格到指定的长度。

您可以考虑将类型说明符更改为SqlDbType.VarChar:它将匹配存储过程中的参数声明,您不会发现自己需要修剪字符串中的尾随空格以使其有用。


2
投票

尝试使用以下代码:

Parameter[param number].Size = 200;


0
投票

SqlDbType.Char改为SqlDbType.VarChar

这里:

scom.Parameters.Add("@User_ID", SqlDbType.Char, 8).Direction = ParameterDirection.Output;

scom.Parameters.Add("@User_Name", SqlDbType.Char, 120).Direction = ParameterDirection.Output;

-1
投票

据我所知,.net中的字符只有一个字符长。因此,您需要将参数类型更改为varchar

scom.Parameters.Add("@User_ID", SqlDbType.Varchar, 8).Direction = ParameterDirect
© www.soinside.com 2019 - 2024. All rights reserved.