在CROSS APPLY语句中执行动态查询?

时间:2018-06-12 15:49:35

标签: sql sql-server-2008

假设:

  • @Records 包含整数ID列表
  • #Columns 包含来自INFORMATION_SCHEMA.COLUMNS的信息,用于多个表(以及其他一些内容)

我试图遍历@Records并将列值转换为备份表。例如:

DECLARE @KeyId
SET @KeyId = 1
DECLARE @Records (id int)
INSERT INTO @Records VALUES (1),(2),(3)

DECLARE #Columns (ColName varchar(100),ColType varchar(100),DataTable varchar(100),DataSchema(100))
INSERT INTO #Columns (ColName,ColType,DataTable,DataSchema) VALUES
('Column1','int','Table1','dbo.'),
('Column2','varchar(50)','Table1','dbo.'),
('Column3','varchar(10)','Table2','dbo.'),
('Column3','int','Table2','dbo.')

CREATE TABLE Table1 (id int, Column1 int, Column2 varchar(50))
CREATE TABLE Table2 (id int, Column3 varchar(10), Column4 int)

INSERT INTO Table1 VALUES (1,1,'test1'),(2,2,'test2')
INSERT INTO Table2 VALUES (1,'test3',3),(2,'test4',4)

应从

转出
Table1                  Table2
id|Column1|Column2      id|Column3|Column4
__________________      __________________
1 |1      |'test1'      1 |'test3'|3
2 |2      |'test2'      2 |'test4'|4

 KeyId|ColName  |ColValue|DataTable|DataSchema
_______________________________________________
     1|'Column1'|'1'     |'Table1' |'dbo.'|
     1|'Column2'|'test1' |'Table1' |'dbo.'|
     1|'Column3'|'test3' |'Table2' |'dbo.'|
     1|'Column4'|'3'     |'Table2' |'dbo.'|
     2|'Column1'|'2'     |'Table1' |'dbo.'|
     2|'Column2'|'test2' |'Table1' |'dbo.'|
     2|'Column3'|'test4' |'Table2' |'dbo.'|
     2|'Column4'|'4'     |'Table2' |'dbo.'|
DECLARE @r int
WHILE EXISTS(SELECT TOP 1 * FROM @Records)
BEGIN
    SET @r = (SELECT TOP 1 * FROM @Records)
    SELECT @KeyId,col.ColName,colValue,col.ColType,col.DataTable,col.DataSchema
    FROM #Columns col
        CROSS APPLY(
            EXEC ('SELECT '+col.ColName+' FROM '+col.DataSchema+col.DataTable+' WHERE '+'Id'+' = '+@r)
        ) x(colValue)
    DELETE TOP(1) FROM @Records
    @KeyId += 1
END

不幸的是,' EXEC [...]'在这种情况下显然不允许声明(我认为这是合理的)。但是,像是

CROSS APPLY(
    SELECT '1'
)

给出

     KeyId|ColName  |ColValue|DataTable|DataSchema
_______________________________________________
     1|'Column1'|'1'     |'Table1' |'dbo.'|
     1|'Column2'|'1'     |'Table1' |'dbo.'|
     1|'Column3'|'1'     |'Table2' |'dbo.'|
     1|'Column4'|'1'     |'Table2' |'dbo.'|
     2|'Column1'|'1'     |'Table1' |'dbo.'|
     2|'Column2'|'1'     |'Table1' |'dbo.'|
     2|'Column3'|'1'     |'Table2' |'dbo.'|
     2|'Column4'|'1'     |'Table2' |'dbo.'|

格式化我的确切方式,除了' 1'而不是我需要的价值。

我可以采取一些方法来做同样的事情:

For each @Record
    For each col.DataTable
        For each col.ColName
            get the Column value

还是在那个地方执行动态选择的方法?

0 个答案:

没有答案