简体   繁体   English

循环遍历列SQL

[英]Loop through columns SQL

I'm looking for a way to loop through the columns of a table to generate an output as described below. 我正在寻找一种循环表的列来生成输出的方法,如下所述。

The table looks like that: 该表看起来像这样:

ID  Name     OPTION1 OPTION2 OPTION3 OPTION4 OPTION5
1   MyName1  1       0       1       1       0
2   MyName2  0       0       1       0       0

And the output looks like that: 输出看起来像这样:

MyName1 -> OPTION1, OPTION3, OPTION4
MyName2 -> OPTION3

Any directions of doing this simply would be greatly appreciated. 这样做的任何方向都将非常感激。 Otherwise, I suppose I'll have to use a cursor or a temporary table... The database engine is MSSQL. 否则,我想我将不得不使用游标或临时表...数据库引擎是MSSQL。 The reason I'm doing formatting at the database level is to feed its output into a limited programmable environment. 我在数据库级别进行格式化的原因是将其输出提供给有限的可编程环境。

Update : the ouput can by in any form, a string or rows of strings. 更新 :输出可以以任何形式,一串或多行字符串。

Update : Would the be a way to accomplish that by building a string using @str = @str + ... ? 更新 :通过使用@str = @str + ...构建字符串是否可以实现这一目标?

Update : I changed the output... this should be easier. 更新 :我更改了输出...这应该更容易。

Thanks! 谢谢!

您可能想看一下PIVOT Tables。

Well, in case of a known number of columns, you can do: 那么,如果列数已知,您可以执行以下操作:

SELECT  
  MyName + " ->"
  + case OPTION1 when 1 then ' OPTION1' else '' end
  + case OPTION2 when 1 then ' OPTION2' else '' end
  + ...
FROM
 Table

If columns are unknown when you create the query - I'd probably still go that way with some dynamically created SQL. 如果在创建查询时列未知 - 我可能仍然会使用一些动态创建的SQL。 The advantage is that the code probably does what you wants and is very simple. 优点是代码可能做你想要的并且非常简单。

You could build a dynamic statement using the system catalog: 您可以使用系统目录构建动态语句:

http://msdn.microsoft.com/en-us/library/ms189082.aspx http://msdn.microsoft.com/en-us/library/ms189082.aspx

Since you don't go into the specific needs of why you want to be able to do this I can't be certain, but usually when I see this kind of question there are two things that I think of: 既然你没有考虑到为什么你希望能够做到这一点的特定需求,我无法确定,但通常当我看到这类问题时,我会想到两件事:

  1. You need to normalize your database. 您需要规范化数据库。 Maybe "Option1", "Option2" etc. have nothing in common, but there is also a good chance that they are a repeating group within your table. 也许“Option1”,“Option2”等没有任何共同之处,但也很有可能它们是你表中的重复组。

  2. Handle display issues in the display layer of your application - ie the front end, not the database. 处理应用程序显示层中的显示问题 - 即前端,而不是数据库。

As I said, maybe these don't apply in your case for some specific reason, but it seems like it from what I've read of your question. 正如我所说,也许这些因某些特定原因不适用于你的情况,但它似乎是我从你的问题中读到的。

If using pivot table, you must make sure all of your "Option" columns have the same data type and length. 如果使用数据透视表,则必须确保所有“选项”列具有相同的数据类型和长度。

I would suggest the following answer: 我建议以下答案:


IF NOT EXISTS( SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME      
 = 'TABLE1' ) 
create table table1
(
   name nvarchar(50),       
   colvalue nvarchar(50)
)
else
  truncate table table1

declare @table nvarchar(50)
set @table = 'yourtable'

declare @column table
(
   ID integer identity,
   colname nvarchar(20)
)


insert into @column
SELECT c.name FROM sys.tables t 
JOIN sys.columns c ON t.Object_ID = c.Object_ID 
WHERE t.Name = @table 
and c.name in ('Option1','Option2','Option3','Option4','Option5')

declare @minID integer, @maxID integer
declare @cmd nvarchar(max)  
declare @col nvarchar(20)
declare @SQLStr nvarchar(max)

select @minID = MIN(ID), @maxID= MAX(ID)
from @column

while @minID <= @maxID
begin
    select @col = colname
    from @column
    where ID = @minID

    set @SQLStr =    
    'insert into table1 (name, colvalue)
    select name,' + @col + '
    from ' + @table + ' 
    where ' + @col + ' <> 0'    

    exec(@SQLStr)

    set @minID = @minID + 1
end

select distinct name, STUFF(
(SELECT  ',' + a.colvalue  AS [text()]
from Table1  a
where a.name = b.name
Order by a.colvalue
for xml PATH('')),1,1,''    ) AS Comments_Concatenated
from Table1 b
group by name, colvalue
ORDER BY name

You just have to modify the @table by putting in your table name and the list of the column you need before insret into @column. 你只需要在插入@column之前输入你的表名和你需要的列列表来修改@table。

No matter what data type you are, it will working fine. 无论您使用何种数据类型,它都能正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM