SQL Server选择除指定名称之外的数据库中的所有列

时间:2015-03-05 10:49:04

标签: sql sql-server sql-server-2012

我尝试了以下SQL语句,但仍然收到了我想要排除的名称的输出列。我在这里做错了什么?

DECLARE @SQL AS VarChar(MAX)
SET @SQL = ''

SELECT @SQL = @SQL + 'SELECT * FROM ' + A.TABLE_SCHEMA + '.[' + A.TABLE_NAME + ']' + CHAR(13)
FROM INFORMATION_SCHEMA.TABLES AS A JOIN INFORMATION_SCHEMA.columns AS B ON A.TABLE_NAME = B.TABLE_NAME
WHERE column_name NOT IN ('rowstamp')

EXEC (@SQL)

2 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @SQL AS VarChar(MAX)
SET @SQL = ''

SELECT @SQL = @SQL + 'SELECT ' + c.Columns + ' FROM '  + A.TABLE_SCHEMA + '.[' + A.TABLE_NAME + ']' +  CHAR(13) 

FROM INFORMATION_SCHEMA.TABLES AS A

CROSS APPLY (SELECT STUFF((SELECT ',' + QUOTENAME(Column_Name) 
             FROM INFORMATION_SCHEMA.columns B WHERE A.TABLE_NAME = B.TABLE_NAME AND B.column_name NOT IN ('rowstamp')
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'') AS Columns) c

PRINT     @SQL    

答案 1 :(得分:0)

你不应该保留*。试试这个

DECLARE @SQL AS VARCHAR(MAX)

SET @SQL = ''

SELECT @sql += 'SELECT ' + column_name + ' from '
               + A.TABLE_SCHEMA + '.[' + A.TABLE_NAME + ']'
               + Char(13)
FROM   INFORMATION_SCHEMA.TABLES AS A
       JOIN INFORMATION_SCHEMA.columns AS B
         ON A.TABLE_NAME = B.TABLE_NAME
WHERE  column_name NOT IN ( 'rowstamp' )

EXEC (@sql)