2016-12-07 66 views
0

我有兩個逗號分隔符的字符串,如Username = "Adam Hughes, Petro Camp"Email Addresses = "[email protected],[email protected]"字符串逗號插入到SQL中的多行中

我要插入到表1條通話記錄,其中有Username ,Email Address, SourceId,DateStamp如表中的列。

我想在表中插入一行:Adam Huges [email protected] 0 '2016-12-06'和Next Row:Petro Camp [email protected] 0 '2016-12-06'

如何達致這?可這在C#中進行,並推到SQL數據庫?

+0

能否請你告訴它的數據庫和語言。如果你希望做這個代碼端或SQL腳本? – Swetha

回答

0
DECLARE @USERNAME VARCHAR(MAX) = 'test1,test2'; 
DECLARE @EMAILID VARCHAR(MAX) = 'test6,testr3' ; 
DECLARE @lenuser INT; 
DECLARE @lenemailid INT; 
DECLARE @startIndex INT = 0; 
declare @indexemail INT = 0; 
DECLARE @endIndex INT; 
DECLARE @startEmailIndex INT = 0; 
DECLARE @endEmailIndex INT; 

WHILE @startIndex <= LEN(@USERNAME) AND @startEmailIndex <= LEN(@EMAILID) 
    BEGIN 
    SELECT @endIndex = charindex(',',@USERNAME,@startIndex); 
    SELECT @endEmailIndex = charindex(',',@EMAILID,@startEmailIndex); 
    if @endIndex = 0 
    begin 
    SELECT @endIndex = LEN(@USERNAME); 
    end 
    if @endEmailIndex = 0 
    begin 
    SELECT @endEmailIndex = LEN(@EMAILID); 
    end 
    INSERT INTO dbo.TABLE_1 VALUES(SUBSTRING(@USERNAME,@startIndex,@endIndex), SUBSTRING(@EMAILID,@startEmailIndex,@endEmailIndex)); 

    SELECT @startIndex = @endIndex +1; 
    SELECT @startEmailIndex = @endEmailIndex +1; 
    END 

這應該work.But可以通過提取上述的功能分割操作除去上面的冗餘。只是你的表名替換TABLE_1並在需要的INSERT語句添加其他列

相關問題