将标量从SQL Server返回到C#

时间:2011-07-15 16:43:34

标签: c# .net sql sql-server-2008 stored-procedures

我试图从这样的数据库中返回标量:

DbConnection cn = GetConnection2();
cn.Open();

// stored procedure
DbCommand cmd = GetStoredProcCommand(cn, "GetReason");
DbParameter param;

param = CreateInParameter("Reason_Number", DbType.String);
param.Value = number;
cmd.Parameters.Add(param);

param = CreateOutParameter("Result", DbType.String);
param.Direction = ParameterDirection.Output;
cmd.Parameters.Add(param);

cmd.ExecuteScalar();

string reason;
reason = cmd.Parameters["@Result"].Value.ToString();

if (cn.State == ConnectionState.Open)
   cn.Close();

return reason;

这是我的存储过程:

-- =============================================
-- Create date: Today
-- Description: Input Reason # and Return Full Reason Name
-- =============================================
ALTER PROCEDURE [dbo].[GetReason]
    @Reason_Number nvarchar(50),
    @Result nvarchar(50) output  
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT @Result = Field1 
    FROM dbo.Reasons
    WHERE Field1 LIKE @Reason_Number + '%';
END

我在ExecuteScalar行收到错误:

  

发生了System.InvalidOperationException   Message =“String [1]:Size属性的大小无效。”

我做错了什么?

2 个答案:

答案 0 :(得分:4)

如果您想使用ExecuteScalar,您的存储过程需要从SELECT返回单行单列:

ALTER PROCEDURE [dbo].[GetReason]
    @Reason_Number nvarchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT Field1 
    FROM dbo.Reasons
    WHERE Field1 LIKE @Reason_Number + '%';
END

然后你的代码需要读取该值:

var returnedValue = cmd.ExecuteScalar();

并从那里使用它。当然,在这种情况下,您也不需要在C#代码中使用OUTPUT参数....

警告:您的存储过程中的SELECT 可能可能会返回多行。您可能希望在选择中添加TOP 1 - 只是为了安全起见:

    SELECT TOP 1 Field1 
    FROM dbo.Reasons
    WHERE Field1 LIKE @Reason_Number + '%';

答案 1 :(得分:1)

只需在存储过程的末尾添加另一个语句,然后删除OUTPUT参数

SELECT @Result as 'Result'