Two solutions for SQL server batch insert and update

Source: Internet
Author: User

Copy codeThe Code is as follows:
. Cursor Mode 1 DECLARE @ Data NVARCHAR (max)
SET @ Data = '1, tanw; 2, keenboy '-- Id, Name

DECLARE @ dataItem NVARCHAR (100)
DECLARE data_cursor cursor for (SELECT * FROM split (@ Data ,';'))
OPEN data_cursor
Fetch next from data_cursor INTO @ dataItem
WHILE @ FETCH_STATUS = 0
BEGIN
DECLARE @ Id INT
DECLARE @ Name NVARCHAR (50)

DECLARE dataItem_cursor cursor for (SELECT * FROM split (@ dataItem ,','))
OPEN dataItem_cursor
Fetch next from dataItem_cursor INTO @ Id
Fetch next from dataItem_cursor INTO @ Name
CLOSE dataItem_cursor
DEALLOCATE dataItem_cursor

/*
Perform logical processing, insert, or update operations here...
*/
END

CLOSE data_cursor
DEALLOCATE data_cursor

Copy codeThe Code is as follows:
. While Mode
DECLARE @ Data NVARCHAR (max)
SET @ Data = 'tanw, keenboy '-- Id, Name

DECLARE @ Temp TABLE
(
Id int identity (1, 1 ),
Name NVARCHAR (50)
)
DECLARE @ Id INT
DECLARE @ Name NVARCHAR (50)
DECLARE @ Results NVARCHAR (MAX) SET @ Results =''
Insert into @ Temp SELECT (SELECT * FROM split (@ Data ,';'))

While exists (SELECT * FROM @ Temp)
BEGIN
Select top 1 @ Id = Id, @ Name = Name from @ Temp
Delete from @ Temp where [id] = @ Id
SET @ Results = @ Results + @ Name + ','

/*

Perform logical processing, insert, or update operations here...

*/
END
SELECT @ Results

For a simple single table batch insert operation, the above method is not required

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.