使用sp_executesql返回null的存储过程输出

时间:2017-03-24 23:28:40

标签: sql-server stored-procedures sp-executesql

我正在使用以下过程动态获取表名,模式名称和数据库名称以生成SELECT语句。当我执行此存储过程而不在任何地方分配@select_statementOUT时,它工作正常。

但是,OUTPUT中的@select_statement值将返回NULL。我希望@select_statement变量返回输出字符串。我不知道在哪里放@select_statementOUT以便它取出字符串。

这是代码:

ALTER PROCEDURE dbo.selectTableAttributes
    @database_name Nvarchar(255),
    @schema_name Nvarchar(255),
    @table_name Nvarchar(255),
    @select_statement nvarchar(MAX) OUT
AS
BEGIN
    DECLARE @query1 nvarchar(MAX), @query2 nvarchar(MAX), 
            @query3 nvarchar(MAX), @query4 nvarchar(MAX), 
            @querydb nvarchar(MAX), @query nvarchar(MAX)

    SET @querydb = N'USE ' + @database_name

我尝试在下面分配@select_statementOUT,这会导致错误 - 'sql_statement'附近的语法不正确& 'tbl_custom_data'

附近的语法不正确
    SET @query1 = N' Select @select_statementOUT =
concat(''select case when count(*) > 100 then ''''transaction'''' else  ''''reference'''' end as cloud_content_type, min('',
case when cloud_transaction_column is not null then cloud_transaction_column
else ''1'' end,'')  as cloud_transaction_start_date,'',
char(39),
case when cloud_transaction_column is not null then cloud_transaction_column
else ''1'' end,
char(39),
'' as cloud_transaction_column,'',
char(39),
cloud_load_type,
char(39),
'' as cloud_load_type,'',
char(39),
table_type,
char(39),
''as table_type '',
'' from '', tbl_details) sql_statement '


    SET @query2 = N'From (Select
tbl_details,
cloud_transaction_column,
case ............ continued .....................................
where  col.table_name=''' + @table_name

    SET @query3 = N'''
and col.TABLE_SCHEMA=''' + @schema_name

    SET @query4 = N'''
) tbl_columns
where cloud_transaction_seq is not null
group by tbl_details)
Tbl_col_group
) tbl_final_data
) tbl_custom_data'

    SET @query = @querydb + @query1 + @query2 + @query3 + @query4

    EXEC sp_executesql @query, N'@database_name Nvarchar(255),
                                 @schema_name Nvarchar(255),
                                 @table_name Nvarchar(255),
                                 @select_statementOUT nvarchar(MAX) OUTPUT',
                      @database_name, @schema_name,
                      @table_name,  
                      @select_statementOUT = @select_statement OUTPUT

END

0 个答案:

没有答案