这是使用表值参数执行此操作的方法。这些是在 SQL 2008 中引入的,因此如果您选择走这条路线,那么该版本将非常适合您的解决方案。在这个测试场景中,我正在制作一个主表和一个相关表,其中的外键指向主表。
首先,创建表数据类型:
CREATE TYPE primary_tbltype AS TABLE
(personkey int NOT NULL PRIMARY KEY,
firstname varchar(30),
lastname varchar(30))
CREATE TYPE related_tbltype AS TABLE
(fk_personkey int NOT NULL,
accountnum varchar(30),
accountbalance money)
创建您的存储过程:
CREATE PROCEDURE MySproc
@PrimaryTable primary_tbltype READONLY,
@RelatedTable related_tbltype READONLY
AS
BEGIN
DECLARE @CurrentKey INT
DECLARE @FirstName VARCHAR(30)
DECLARE @LastName VARCHAR(30)
DECLARE @AccountTotal MONEY
DECLARE PersonCursor CURSOR LOCAL FAST_FORWARD FOR
SELECT personkey, firstname, lastname FROM @PrimaryTable
OPEN PersonCursor
FETCH NEXT FROM PersonCursor INTO @CurrentKey, @FirstName, @LastName
WHILE @@FETCH_STATUS= 0 BEGIN
SELECT @AccountTotal = SUM(accountbalance) FROM @RelatedTable
WHERE fk_personkey = @CurrentKey
PRINT @FirstName + ' ' + @LastName + ' - account total: ' + CONVERT(VARCHAR(30), @AccountTotal)
FETCH NEXT FROM PersonCursor INTO @CurrentKey, @FirstName, @LastName
END
END;
这里有一些测试数据可以尝试一下:
DECLARE @primaryTVP primary_tbltype
DECLARE @relatedTVP related_tbltype
INSERT INTO @primaryTVP values (1, 'John', 'Cleese')
INSERT INTO @primaryTVP values (2, 'Eric', 'Idle')
INSERT INTO @primaryTVP values (3, 'Graham', 'Chapman')
INSERT INTO @relatedTVP values (1, '29310918', 28934.33)
INSERT INTO @relatedTVP values (2, '123123', 3418.11)
INSERT INTO @relatedTVP values (2, '33333', 666.66)
INSERT INTO @relatedTVP values (3, '554433', 22.22)
INSERT INTO @relatedTVP values (3, '239482', 151515.15)
EXEC MySproc @primaryTVP, @relatedTVP;
此处介绍了使用 TVP 的一些优点,并且它们还能够参与基于集合的操作。