子查询定义选择列表

时间:2014-03-27 22:10:51

标签: sql-server select sql-server-2008-r2

SQLFiddle

我想使用"子查询"定义我想要选择的表列。 Fields表FieldName列包含EDIFields表的列名以及其他列。

类似于以下内容:

SELECT ( SELECT FieldName 
         FROM FieldsTable ft 
         WHERE ft.FormatID = @FormatID 
           AND ft.Active != 0 ) 
From EDIFields
Where ...

是否可以在sql server 2008 r2中执行此操作,还是可以通过其他方式获得我想要的结果?

示例输出:

@Active = 1
@FormatID = 1
PONUM  QTY
PO1    1
PO2    3
PO3    2

@Active = 1
@FormatID = 2
PONUM  TRANSID  MSG
PO1    T1       msg1
PO2    T1       msg2
PO3    T2       msg3

@Active = 1
@FormatID = 3    
TOTAL
56.65
67.43
100

初始表格如下:

EDIFields -

PONUM   TRANSID QTY MSG TOTAL
PO1     T1          1   msg1    56.65
PO2     T1          3   msg2    67.43
PO3     T2          2   msg3    100

字段 -

FIELDID FIELDNAME   FORMATID   ACTIVE
1           PONum           1      1
2           TransID         1      0
3           Qty             1      1
4           PONum           2      1
5           TransID         2      1
6           Msg             2      1
7           Total           3      1

2 个答案:

答案 0 :(得分:1)

我认为唯一的方法是构建动态SQL语句

     DECLARE @SQL as nvarchar(MAX)
DECLARE @COLUMNLIST as nvarchar(MAX)

SELECT @COLUMNLIST = coalesce(@COLUMNLIST +',', '') + '[' + FieldName + ']'  
         FROM FieldsTable ft 
         WHERE ft.FormatID = @FormatID 
           AND ft.Active != 0

set @SQL =  'select ' +  @COLUMNLIST + ' FROM EDIFields'
exec sp_executesql @SQL

答案 1 :(得分:0)

这是存储过程 -

Create  procedure getResults(
@Active int,
@FormatID int
)
AS
BEGIN
Declare @srcTable nvarchar(100)
Declare @ColumnList nvarchar(max)
Declare @sqlCmd nvarchar(max)
Set @srcTable = 'EDIFields'
Set @ColumnList = ''
Set @sqlCmd = 'SELECT '
-- Get the field list as a comma separated value
Select @ColumnList =  @ColumnList + fieldName + ','
from fields
where (formatId = @FormatID and active = @Active) 
-- Remove comma from last position of columnList
Set @ColumnList = LEFT(@ColumnList, LEN(@ColumnList) - 1)
-- Now add these columns to the sqlCmd
Set @sqlCmd = @sqlCmd + @ColumnList + ' FROM ' + @srcTable
-- Now your sql statement is ready to be executed
exec sp_executesql @sqlCmd
END