循环遍历Ids列表并执行动态插入语句

时间:2017-10-09 08:58:19

标签: sql-server loops

我想循环遍历国家/地区ID列表并为每个ID执行插入语句。

我需要一个循环,其中每个国家/地区ID都可以作为循环中的变量访问,我可以将其连接到动态SQL查询

CREATE TABLE [dbo].countryIds(
 CountryId INT IDENTITY(1,1)
)

SET IDENTITY_INSERT [dbo].countryIds ON
INSERT [dbo].countryIds (CountryId) VALUES (8)
INSERT [dbo].countryIds (CountryId) VALUES (13)
SET IDENTITY_INSERT [dbo].countryIds OFF

WHILE EXISTS (SELECT CountryId FROM CountryIds)
BEGIN
-- INSERT INTO anotherTable custom sql where country ID = CountryId
END

我尝试了一段时间的存在循环,但这无限循环。

如何实现这一目标?

3 个答案:

答案 0 :(得分:0)

尝试在存在https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql

时使用光标
CREATE TABLE [dbo].countryIds(
 CountryId INT IDENTITY(1,1)
)

SET IDENTITY_INSERT [dbo].countryIds ON
INSERT [dbo].countryIds (CountryId) VALUES (8)
INSERT [dbo].countryIds (CountryId) VALUES (13)
SET IDENTITY_INSERT [dbo].countryIds OFF

declare @CountryId int

declare country_cursor  cursor for
  select CountryId from CountryIds 

open country_cursor

fetch next from country_cursor
  into @CountryId

while @@fetch_status = 0
begin
  --INSERT INTO anotherTable custom sql where country ID = CountryId

  fetch next from country_cursor
    into @CountryId
end

close country_cursor
deallocate country_cursor

答案 1 :(得分:0)

首先,我建议手动交易,看看在实际提交之前是否一切正常:

BEGIN TRAN;

SQL

ROLLBACK or COMMIT;

现在问题: 这应该通过游标完成(以下是一个简单的游标示例)

DECLARE @CountryIds int

-- the declaration of the cursor itselfdeclare a cursor
DECLARE cursor_for_insert CURSOR FOR 
SELECT CountryId FROM CountryIds

-- open the cursor and fetch first row into variable
OPEN cursor_for_insert
FETCH NEXT FROM insert_cursor INTO CountryIds 

-- run till there is a row to get
WHILE @@FETCH_STATUS=0
BEGIN

-- do your insert here
-- INSERT INTO anotherTable custom sql where country ID = CountryId

END
-- don't forget to close it an unallocate it otherwise it will be still allocated! 
CLOSE cursor_for_insert
DEALLOCATE cursor_for_insert
GO

答案 2 :(得分:0)

在SQL中使用循环是一种不好的做法,使用多行:

INSERT INTO anotherTable (...)
SELECT ...
FROM anotherTable a
INNER JOIN countryIds
WHERE countryID = CountryId