在SQL中为数据列表插入多行

时间:2018-08-06 09:23:31

标签: sql sql-server sql-server-2014

我正在尝试将数据插入到基于SQL Management Studio 2014中另一个表的表中。我有一个用户列表,该列表的用户数为9500。对于每个用户,我想在另一个表中插入多个数据(详细数据)。这是我的情况:

DECLARE @MAXID INT, @Counter INT
DECLARE @TEMP1 TABLE (
    ROWID int identity(1,1) primary key,
    userName nvarchar(50),
    userEmail nvarchar(256)
)

insert into @TEMP1
select UserName, UserEmail from utblUsers

SET @COUNTER = 1
SELECT @MAXID = COUNT(*) FROM @TEMP1
declare @userEmail nvarChar(256),@UserName nvarchar(50)
WHILE (@COUNTER <= @MAXID/2)
BEGIN

    SELECT @userEmail=UserEmail, @UserName=UserName
    FROM @TEMP1 AS PT
    WHERE ROWID = @COUNTER
    exec sifms.dbo.sp_UserDetailInsert @UserName, @userEmail
    SET @COUNTER = @COUNTER + 1

END;

在循环中,我正在调用sp_UserDetailInsert,它将数据插入我的详细信息表,如下所示:

DECLARE @cnt INT = 1,@sumAmount bigint, @deductedFromId int;
WHILE @cnt <= 5
BEGIN
    if @cnt=1  
    begin 
        -------Doing some calculation for SumAmount and get the deductedFromID
        Insert into utblUserDetails values (@UserName,@userEmail, @sumAmount, @deductedFromId)
    end
    else if @cnt=2  
    begin 
        -------Doing some calculation for SumAmount and get the deductedFromID
        Insert into utblUserDetails values (@UserName,@userEmail, @sumAmount, @deductedFromId)
    end
    .
    .
    .
    .
    else @cnt=5  
    begin 
        -------Doing some calculation for SumAmount and get the deductedFromID
        Insert into utblUserDetails values (@UserName,@userEmail, @sumAmount, @deductedFromId)
    end
END

我的查询执行了几分钟完全没问题。但是问题是

  1. 查询执行速度非常慢
  2. 执行几分钟后,SQL Management Studio将关闭。

我尝试使用

清除缓存
DBCC FREESYSTEMCACHE ('ALL') 
DBCC FREESESSIONCACHE
DBCC FREEPROCCACHE

但是结果仍然相同。我也尝试过使用游标,但是游标要重得多,并且它比循环消耗更多的内存。因为循环比光标轻,所以在这种情况下我更喜欢循环,我只想先获取用户详细信息,然后再将复杂性降至最低。

0 个答案:

没有答案