如何遍历临时表循环以取出SQL中的每个列名?

时间:2014-10-09 06:59:22

标签: c# mysql sql sql-server

我在sql中有一个临时表。

CREATE TABLE #Temporary(ColumnNames varchar(100),IsActive varchar(100))

insert into #Temporary(ColumnNames,IsActive)
select  aa.Name,bb.IsActive  from tableAA aa join tableBB bb on aa.Id = bb.Id

ColumnNames IsActive 
Name           1
Description    1
Id             0

现在我想遍历每个ColumnNames并将该值传递给另一个select查询 如果IsActive = 1

,则使用join从另一个表中取出相关值

例如,我在c#代码中完成了我需要在SQL代码中转换此代码

new string s1 
forloop(END OF ALL COLUMNS FROM #Temporary){
    if(isactive=0)
    concatinate  string s1 +=cloumnIndex[i]+','
    else
    concatinate  string s1 +='(select resourcetableValue from ResourcesTable as t where contry.'+cloumnIndex[i]+'=t.resourcetableKey),'
}

EXEC('select  '+string s1 +' from vwCountry as contry')  

我需要创建String s1,它将取出Temp Table中的所有列名,而for循环else部分将使用join填充值,最后EXEC语句立即执行所有查询

2 个答案:

答案 0 :(得分:1)

按顺序编写循环""可以完成:

declare @s nvarchar(4000) = '';
select @s = @s + case IsActive when 0 then ColumnNames + ','
    else '(select resourcetableValue from ResourcesTable as t where contry.'
        + ColumnNames + '=t.resourcetableKey),' end
from #Temporary

exec ('select ' + @s + ' from vwCountry as contry')

您可能希望删除selectexec之间的最后一个逗号,但

答案 1 :(得分:1)

试试这个

 DECLARE @i  INT=1,
            @s1 NVARCHAR(max)=''

    WHILE(@i<=@@ROWCOUNT)
    BEGIN
    SELECT @s1+= CASE WHEN isactive=1 THEN '(select resourcetableValue .......<your condition>'
              ELSE ''
    from #temporary WHERE id=@i

    SET @i=@i+1
    END
    exec sp_executesql @S1