2014-03-27 90 views
0

SQLFiddle子查询定义选择列表

我想使用“子查询”来定义我想选择的表列。 “字段”表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 
+0

您好,有什么是你所期望的输出? –

+0

我在sqlfiddle中有这个,但我会复制并粘贴到一个编辑。 – Archangel33

+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 
+0

这干净简单,工作谢谢。 – Archangel33

+1

真棒我很高兴它是有用的:-)它一直是我最喜欢的查询...原来我从Pinal戴夫查询。 http://blog.sqlauthority.com/2008/06/04/sql-server-create-a-comma-delimited-list-using-select-clause-from-table-column/。 Pinal通常是我95%的SQL问题得到解答的地方。 –

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 
+0

帮助我将列转换为CSV的关键文章 - https://stackoverflow.com/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in -sql-server-2005 –

+0

执行样例 - 'exec getResults 1,1'。我希望你能喜欢 !很好。我喜欢 !顺便说一句,我不使用任何像“COALESCE”这样的函数。 –

+0

这工作得很好,但我只能接受一个答案。 – Archangel33