开发者

Stored procedure reading xml, any way better to do it? SQL SERVER 2008

开发者 https://www.devze.com 2023-04-07 17:27 出处:网络
I do something like this: CREATE PROCEDURE [dbo].[InsertStudents] ( @students nvarchar(max) ) AS DECLARE @studentstable TABLE

I do something like this:

CREATE PROCEDURE [dbo].[InsertStudents]
(
    @students nvarchar(max)
)
AS
DECLARE @studentstable TABLE
(
    RowIndex int,
    FirstName nvarchar(50),
    LastName nvarchar(50),
    Number nvarchar(20),
    IdSchool int
)
DECLARE @xmldata xml
SET @xmldata = @students
INSERT INTO @studentstable
SELECT S.Stud.query('./RowIndex').value('.','int') RowIndex, 
       S.Stud.query('./FirstName').value('.','nvarchar(50)') FirstName,
       S.Stud.query('./LastName').value('.','nvarchar(50)') LastName,
       S.Stud.query('./Number').value('.','nvarchar(50)') Number,
       S.Stud.query('./IdSchool').value('.','int') IdSchool,
FROM @xmldata.nodes('/Students/Student') AS S(Stud)   

 DECLARE @totalrows int
 DECLARE @currentrow int
 DECLARE @totalinserts int

 DECLARE @currentfirstname nvarchar(50)
 DECLARE @currentlastname nvarchar(50)
 DECLARE @currentnumber nvarchar(20)
 DECLARE @currentidschool int

 D开发者_StackOverflow中文版ECLARE @insertresult int

 SET @totalinserts = 0
 SET @totalrows=(SELECT COUNT(*) FROM @studentstable)
 SET @currentrow=0

 WHILE(@currentrow<@totalrows) BEGIN
    SELECT @currentfirstname = FirstName, @currentlastname = LastName, @currentnumber = Number, @currentidschool = IdSchool
    FROM @studentstable
    WHERE RowIndex=@currentrow
    EXEC @insertresult = InsertStudent @currentfirstname, @currentlastname, @currentnumber, @currentidschool
    IF @insertresult=0 BEGIN
        SET @totalinserts=@totalinserts+1
    END 
    SET @currentrow = @currentrow + 1
 END
 SELECT @totalinserts

InsertStudent returns 0 if insert worked or 1 if there is already a student with that number.

Isn't there any way to do it without messing with that variable table?


Something like this using merge.

merge Student
using (select S.Stud.query('./RowIndex').value('.','int') RowIndex, 
              S.Stud.query('./FirstName').value('.','nvarchar(50)') FirstName,
              S.Stud.query('./LastName').value('.','nvarchar(50)') LastName,
              S.Stud.query('./Number').value('.','nvarchar(50)') Number,
              S.Stud.query('./IdSchool').value('.','int') IdSchool
       from @xmldata.nodes('/Students/Student') as S(Stud)) as SXML
on Student.Number = SXML.Number
when not matched then
  insert (FirstName, LastName, Number, IdSchool)
    values (SXML.FirstName, SXML.LastName, SXML.Number, SXML.IdSchool);

select @@rowcount
0

精彩评论

暂无评论...
验证码 换一张
取 消