0

我创建了一个脚本,从 db 表中动态选择列并将其用作 select 语句中的列。但是,我遇到了一个错误“Select 附近的语法不正确”。有人有想法吗?

Table_Sample_Table
ColumnName-SqlColumnName

SqlColumnName Values 
'Salary'
Age
Name
Address

table_to_query_the_data
Columns consist of
Salary
Age
Name
Address

Sample Query
SET @x='Select ' + SELECT STUFF((SELECT ',' + SqlColumnName
            FROM sample_table
            WHERE SqlColumnName ='Salary'
            FOR XML PATH('')) ,1,1,'') AS Txt + 'from table_to_query_the_data'
4

1 回答 1

1

表格不是很清楚,但我认为SET @x应该是这样的;

SET @x= 'SELECT ' + STUFF((SELECT ',' + SqlColumnName
         FROM sample_table
         WHERE SqlColumnName = 'Salary'
         FOR XML PATH('')) ,1,1,'')   + ' FROM table_to_query_the_data'

或者你最好用[]as包装你的列名[col1],[col2],..

SET @x= 'SELECT ' + STUFF((SELECT '],[' + SqlColumnName
         FROM sample_table
         WHERE SqlColumnName = 'Salary'
         FOR XML PATH('')) ,1,2,'')  + '] FROM table_to_query_the_data'
于 2013-03-06T11:00:17.877 回答