字符串逗号在SQL中插入多行

时间:2016-12-07 15:24:36

标签: rows comma

我有两个逗号分隔符字符串,如Username = "Adam Hughes, Petro Camp"Email Addresses = "Adam.huges@test.com,petro.camp@test.com"

我想在表中插入Username ,Email Address, SourceId,DateStamp作为列的日志历史记录。

我想在表格中插入一行:Adam Huges Adam.huges@test.com 0 '2016-12-06'和下一行:Petro Camp petro.camp@test.com 0 '2016-12-06'

如何实现这一目标?这可以在C#中完成并推送到SQl数据库吗?

1 个答案:

答案 0 :(得分: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

这应该可行。但是你可以通过将上面的拆分操作提取到函数来删除上面的冗余。用表名替换table_1并在insert语句中添加所需的其他列