以C#中的字符串格式获取存储过程的输出

时间:2014-12-09 17:32:25

标签: c# sql-server tsql stored-procedures sqlcommand

我有一个返回字符串的存储过程:

DECLARE @SqlStatement VARCHAR(MAX)

SELECT @SqlStatement = 
    COALESCE(@SqlStatement, '') + 'DROP TABLE [TMP].' + QUOTENAME(TABLE_NAME) + ';' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'TMP'

PRINT @SqlStatement

我尝试像这样返回字符串:

var con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBBASE"].ConnectionString);

using (var cmd = new SqlCommand("proSQL", con)
{
    CommandType = CommandType.StoredProcedure
})
{
    cmd.Parameters.Add("SqlStatement", SqlDbType.VarChar);
    var returnParameter = cmd.Parameters.Add("@SqlStatement", SqlDbType.VarChar);
    returnParameter.Direction = ParameterDirection.Output;

    con.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

当我运行代码时,我收到错误:

  

程序proSQL没有参数和参数提供

我不确定我做错了什么。有些人可以告诉我如何以字符串格式获取存储过程的输出吗?

2 个答案:

答案 0 :(得分:0)

SP的变化:

DECLARE @SqlStatement VARCHAR(MAX) OUTPUT 

更改C#代码:

var returnParameter = new SQLParameter("@SqlStatement", SqlDbType.VarChar, -1);
returnParameter.Direction = ParameterDirection.Output; 
cmd.Parameters.Add(returnParameter);

答案 1 :(得分:0)

你的SQL应该是这样的,

CREATE PROCEDURE [GetTableNames]
     @schema NVARCHAR(128)
AS
    SELECT
            [TABLE_NAME]
    FROM
            [INFORMATION_SCHEMA].[TABLES]
    WHERE
            [TABLE_SCHEMA] = @schema
RETURN 0;

然后你可以得到你想要的字符串,

var tableNames = new List<string>();
var con = new SqlConnection(
              ConfigurationManager.ConnectionStrings["DBBASE"].ConnectionString);

using (var cmd = new SqlCommand("GetTableNames", con)
        {
            CommandType = CommandType.StoredProcedure
        })
{                 
    cmd.Parameters.Add("@schema", "TMP");    
    con.Open();
    using (var reader = cmd.ExecuteReader())
    {
        while(reader.MoveNext())
        {
            tableNames.Add(reader.GetString(0))
        }
    }
}

var result = string.Join(
    Environment.NewLine,
    tableNames
        .Select(tn => string.Format("DROP TABLE [TMP].[{0}];", tn))
        .ToArray());