簡體   English   中英

MSSQL INFORMATION_SCHEMA.COLUMNS 成表,然后在 SELECT 語句中使用

[英]MSSQL INFORMATION_SCHEMA.COLUMNS into a table, then use in a SELECT statement

有一個真正的益智游戲打亂了我的想法,有人可以幫忙嗎?

我將所有表列名放入一個表中,並按模板名稱對列名進行分組。

這個想法是我可以選擇 template_1 並且只有那些列名出現在 Select 語句中,例如

-- 模板表 -- -- table1 -

firstname, template_A
lastname, template_A
field3, template_B
location, template_A

似乎如果您從表字段(字符串值)中提取列名,則可以將其 SELECT 作為列。

困難之處在於,由於我有不同的模板,我需要選擇正確的模板,然后讓這些字段為值調用第二個表,例如

-- 數據表 -- -- table2 -

firstname, lastname, location
David, Smith, Glasgow

-- 數據參考模板 -- -- table3 -

table1_field1_id, table2_field1_id

我嘗試先創建一個變量然后運行 ​​SQL,例如

SET @COLS = 'SELECT t1.field, (SELECT ' + t1.field + ' FROM t2)
FROM table1 t1
INNER JOIN table3 t3 ON t1.field1_id = t3.field1_id
INNER JOIN table2 t2 ON t2.field1_id = t3.field1_id
WHERE t1.template = 'template_A'

EXEC SP_EXECUTESQL @COLS

我正在嘗試獲得類似的輸出...

firstname, David
lastname, Smith
location, Glasgow

困難的部分是不同的模板需要加載不同的列

這里的任何解決方案都很難壓縮成單個語句,並且避免某種循環結構也將非常困難。 這是一個涉及游標的解決方案。

順便說一句,使用這樣的方法, table3是多余的。 至少,我最終不需要它。

-- BEGIN TEST DATA

create table table1 (field varchar(max), template varchar(max))
insert into table1 select 'firstname', 'template_A'
insert into table1 select 'lastname', 'template_A'
insert into table1 select 'field3', 'template_B'
insert into table1 select 'location', 'template_A'

create table table2 (firstname varchar(max), lastname varchar(max), location varchar(max))
insert into table2 select 'David', 'Smith', 'Glasgow'
insert into table2 select 'John', 'Hancock', 'Dublin'

-- END TEST DATA

declare @sql nvarchar(max)                     -- Used with sp_executesql
declare @field varchar(max)                    -- Temp variable for cursor
declare @template varchar(max) = 'template_A'  -- Set template name here

-- Temp table for output
create table #tmp (field varchar(max), value varchar(max))

-- BEGIN CURSOR

declare template_assignment cursor for 
select field from table1 where template = @template

open template_assignment  
fetch next from template_assignment into @field  

while @@fetch_status = 0  
begin  
    set @sql = 'insert into #tmp (value) select ' + @field + ' from table2'

    exec sp_executesql @sql

    update #tmp set field = @field where field is null

    fetch next from template_assignment into @field 
end 

close template_assignment  
deallocate template_assignment

-- END CURSOR

select * from #tmp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM