简体   繁体   English

SQL Server 2008使用WHILE LOOP插入

[英]SQL Server 2008 Insert with WHILE LOOP

I have existing records like 我有现有的记录

ID    Hospital ID     Email                Description 
1       15         abc@e.com           Sample Description
2       15         def@dd.com          Random Text

I need to use a WHILE loop to insert rows with Hospital ID changing to a specific value or 32 in this case, while the others(not ID as it is auto generated) remaining constant. 我需要使用WHILE循环来插入医院ID更改为特定值的行或在这种情况下为32,而其他(不是ID,因为它是自动生成的)保持不变。

It should then look like 它应该看起来像

ID    Hospital ID     Email                Description 
1       15         abc@e.com           Sample Description
2       15         def@dd.com          Random Text
3       32         abc@e.com           Sample Description
4       32         def@dd.com          Random Text

Notice the above now has two new rows with ID and Hospital ID different. 请注意,上面现在有两个ID与医院ID不同的新行。 ID is auto generated. ID是自动生成的。

I have several tables where I need to make the same updates. 我有几个表,我需要进行相同的更新。 I don't want to use cursor if I can do this with a while loop. 如果我可以使用while循环执行此操作,我不想使用游标。

EDIT Abandoned while loop as a simpler solution was provided in the accepted answer. 编辑在接受的答案中提供了循环作为更简单的解决方案。

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production. 首先,我想说我100%同意John Saunders,在大多数情况下尤其是在生产中你必须避免使用SQL循环。

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop. 但偶尔作为一次性的事情来填充一个带有一百条记录的表用于测试目的恕我直言,放纵自己使用循环是可以的。

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used 例如,在您的情况下,使用16到100之间的医院ID的记录填充您的表格,并使电子邮件和描述与您可以使用的不同

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be 结果就是

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          user16@mail.com  Sample Description16 
2    17          user17@mail.com  Sample Description17 
...                                                    
84   99          user99@mail.com  Sample Description99 

Assuming that ID is an identity column: 假设ID是标识列:

INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32

Try to avoid loops with SQL. 尽量避免使用SQL循环。 Try to think in terms of sets instead. 试着用套装来思考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM