1

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

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

我究竟做错了什么???

谢谢,尤金

4

1 回答 1

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 建议的实现。

于 2012-07-25T19:51:11.080 回答