2016-08-09 57 views
0

我有以下腳本,我想插入表中,其中列名可以作爲逗號分隔值傳遞。請提出不同的方法來實現以下輸出。插入表中列值作爲逗號定界值傳遞

Declare @col_by_source varchar(250) = 's1,s2,s3', 
    @column_by_target varchar(250) = 'c1,c2,c3', 
    @SQLString nvarchar(max) 


Set @SQLString = 'INSERT INTO [dbo].[sourceTable] (
        ['[email protected]_by_source+'])' 

set @SQLString = @SQLString+' '+'SELECT ' 

Select @SQLString = @SQLString + QUOTENAME(split.a.value('.', 'VARCHAR(100)')) + ' AS '[email protected]_by_source+',' 
FROM (SELECT Cast ('<M>' + Replace(@column_by_target, ',', '</M><M>')+ '</M>' AS XML) AS Data) AS A 
CROSS apply data.nodes ('/M') AS Split(a); 

Set @SQLString = LEFT(@SQLString, LEN(@SQLString) - 1) + ')' 

Set @SQLString = @SQLString + 'FROM tableA_source' 
print @SQLString 

OUTPUT:

INSERT INTO [dbo].[sourceTable] (
       [s1,s2,s3]) SELECT [c1] AS s1,s2,s3,[c2] AS s1,s2,s3,[c3] AS s1,s2,s3 FROM tableA_source 

預期輸出:

INSERT INTO [dbo].[sourceTable] (
      [s1,s2,s3]) SELECT [c1] AS s1, [c2] AS s2,[c3] AS s3 
FROM tableA_source 

回答

0

讓它簡單。在插入時不需要別名....選擇。

嘗試這樣,

DECLARE @col_by_source VARCHAR(250) = 's1,s2,s3' 
    ,@column_by_target VARCHAR(250) = 'c1,c2,c3' 
    ,@SQLString NVARCHAR(max) 

SET @SQLString = 'INSERT INTO [dbo].[sourceTable] (
        ' + @col_by_source + ')' 
SET @SQLString = @SQLString + ' ' + 'SELECT ' 

SELECT @SQLString = @SQLString + QUOTENAME(split.a.value('.', 'VARCHAR(100)')) + ' ,' 
FROM (
    SELECT Cast('<M>' + Replace(@column_by_target, ',', '</M><M>') + '</M>' AS XML) AS Data 
    ) AS A 
CROSS APPLY data.nodes('/M') AS Split(a); 

SET @SQLString = LEFT(@SQLString, LEN(@SQLString) - 1) + '' 
SET @SQLString = @SQLString + 'FROM tableA_source' 

PRINT @SQLString 
+0

INSERT INTO [sourceTable會]( S1,S2,S3 ) SELECT \t '〜N' 爲C1, \t '〜N' AS C2, \t '〜N'AS c3在這種情況下我需要實現別名。你能提出什麼建議嗎? @StackUser – cnayak