我需要一个存储过程,它返回已创建记录的ID结果集。我已经读过SCOPE_IDENTITY只给出了最后一个ID。但我的SQL技能不足以解决这个特殊情况,并将所有ID作为输出。
这就是我现在所拥有的 - 这只能获得最后一条记录的身份
USE AdventureWorks2008;
DELETE FROM [HumanResources].[Shift] where [HumanResources].[Shift].Name='c' or [HumanResources].[Shift].Name='d'
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'ShiftUpdateXml')
DROP PROCEDURE ShiftUpdateXml
GO
CREATE PROCEDURE ShiftUpdateXml
@strXML XML, @ShiftID [tinyint] = NULL OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT [HumanResources].[Shift](Name,StartTime,EndTime) SELECT
TEMP.Name,TEMP.StartTime,TEMP.EndTime
FROM (SELECT
assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
assignreassignro.value('EndTime[1]','time(7)') AS EndTime
FROM @strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP
SET @ShiftID = SCOPE_IDENTITY();
END
GO
DECLARE @ShiftID INT;
DECLARE @XmlVal XML= '<?xml version="1.0"?>
<documentelement>
<assignreassignro>
<Name>c</Name>
<StartTime>10:30:00.0000000</StartTime>
<EndTime>17:30:00.0000000</EndTime>
</assignreassignro>
<assignreassignro>
<Name>d</Name>
<StartTime>11:00:00.0000000</StartTime>
<EndTime>18:00:00.0000000</EndTime>
</assignreassignro>
</documentelement>'
EXEC ShiftUpdateXml @XmlVal,@ShiftID = @ShiftID OUTPUT;
PRINT @ShiftID;
答案 0 :(得分:3)
您正在寻找output
条款。如果你只想要ids,你可以这样做:
DECLARE @ids TABLE (id int);
INSERT [HumanResources].[Shift](Name,StartTime,EndTime)
OUTPUT inserted.Id INTO @ids
SELECT assignreassignro.value('Name[1]', 'nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]', 'time(7)') AS StartTime,
assignreassignro.value('EndTime[1]', 'time(7)') AS EndTime
FROM @strXML.nodes('documentelement/assignreassignro') Documentelement(assignreassignro);
如果您想要其他值,可以将它们添加到表格和INSERT
语句中。
另请注意,您不需要SELECT
的子查询。
答案 1 :(得分:1)
要获得多行,您需要使用插入的表格中的输出:
CREATE PROCEDURE ShiftUpdateXml
@strXML XML
AS
BEGIN
INSERT [Shift](Name,StartTime,EndTime)
output inserted.id
SELECT
TEMP.Name,TEMP.StartTime,TEMP.EndTime
FROM (SELECT
assignreassignro.value('Name[1]','nvarchar(50)') AS Name,
assignreassignro.value('StartTime[1]','time(7)') AS StartTime,
assignreassignro.value('EndTime[1]','time(7)') AS EndTime
FROM @strXML.nodes('documentelement/assignreassignro')Documentelement(assignreassignro)) AS TEMP
END
这样程序将返回ID列表。我在SQL Fiddle
中做了一个例子