sp_executesql不返回值

时间:2012-07-25 17:56:28

标签: sql-server tsql

我需要能够为给定的表提供列列表。 当我运行以下内容时:

DECLARE @ColList Varchar(Max)
DECLARE @TabName varchar(100) = 'CT_CONF'

SELECT  @ColList =  CASE WHEN @ColList IS NULL THEN '''' ELSE @ColList + ',' END + column_name
                    from INFORMATION_SCHEMA.COLUMNS
                    where TABLE_NAME = @TabName
                      and DATA_TYPE not in ('xml','Text','Image','Geometry','Geography')
                      and COLUMN_NAME not in ('LAST_MODIFIED')
                    order by ordinal_position                   

select @ColList

我得到了我需要的输出,但是,当我尝试运行下面的sp_executesql时,我什么也得不到。

DECLARE @TabName varchar(100) = 'CT_CONF'

DECLARE @SQL NVarchar(Max)
DECLARE @ColList Varchar(Max)
Declare @Params nvarchar(Max)

SET @SQL = N'   
            select @ColList = CASE WHEN @ColList IS NULL THEN '''' ELSE @ColList + '','' END + column_name
                    from INFORMATION_SCHEMA.COLUMNS
                    where TABLE_NAME = ''@TabName ''
                      and DATA_TYPE not in (''xml'',''Text'',''Image'',''Geometry'',''Geography'')
                      and COLUMN_NAME not in (''LAST_MODIFIED'')
                    order by ordinal_position
            '

set @Params = N'@ColList varchar(Max) OUTPUT'

EXEC sp_executesql @SQL, @Params, @ColList OUTPUT

select @ColList

我做错了什么???

谢谢, 尤金

1 个答案:

答案 0 :(得分:2)

尝试:

'...
    where TABLE_NAME = ''' + @TabName + '''
...'

或(可能更好):

'...
        where TABLE_NAME =  @TabName
...'
set @Params = N'@TabName varchar(100), @ColList varchar(Max) OUTPUT' 

EXEC sp_executesql @SQL, @Params, @TabName, @ColList OUTPUT

这些只是@Mikael Eriksson在评论中提出的建议。