我的select语句中有一堆记录。我必须为该选择的每一行调用某些存储过程。我知道这是通过游标完成的(我已经在SO上找到了有关此问题的答案-但它们都非常旧了)。我很好奇,今天的现代版本的SQL Server是否还有其他可能性?
我的选择
SELECT USER_KEY, USER_WHK FROM BAUSER WHERE USER_STA = '1'
我的插入内容:
EXEC sp_BAUSCA_BASE
@iUSCA_KEY = NULL
, @iCAET_KEY = 150000003
, @iUSER_KEY = --user key from select
, @iENTE_KEY = 110000001
, @dUSCA_DAT = GETDATE()
, @cUSCA_STA = '1'
, @cUSCA_SRT = '1'
, @iUserId = 160000230
, @cTask = '2'
答案 0 :(得分:4)
您可以使用Cursor存档此要求,我为您制作了一个演示,可能会对您有所帮助。
有关光标的更多信息,您可以访问此link。
演示
DECLARE
@iUSCA_KEY NVARCHAR(50) ,
@iCAET_KEY NVARCHAR(50) ,
@iUSER_KEY NVARCHAR(50) ,
@iENTE_KEY NVARCHAR(50) ,
@dUSCA_DAT DATETIME,
@cUSCA_STA NVARCHAR(50) ,
@cUSCA_SRT NVARCHAR(50) ,
@iUserId INT,
@cTask NVARCHAR(50)
DECLARE MY_data CURSOR LOCAL FAST_FORWARD
FOR
SELECT
iUSCA_KEY,
iCAET_KEY ,
iUSER_KEY ,
iENTE_KEY ,
dUSCA_DAT,
cUSCA_STA,
cUSCA_SRT ,
iUserId ,
cTask
FROM BAUSER WHERE USER_STA = '1'
OPEN MY_data
FETCH NEXT FROM MY_data INTO @iUSCA_KEY,@iCAET_KEY,@iUSER_KEY,@iENTE_KEY,@dUSCA_DAT,@cUSCA_STA,@cUSCA_SRT,@iUserId,@cTask
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_BAUSCA_BASE
@iUSCA_KEY = @iUSCA_KEY
, @iCAET_KEY = @iCAET_KEY
, @iUSER_KEY = @iUSER_KEY
, @iENTE_KEY = @iENTE_KEY
, @dUSCA_DAT = @dUSCA_DAT
, @cUSCA_STA = @cUSCA_STA
, @cUSCA_SRT = @cUSCA_SRT
, @iUserId = @iUserId
, @cTask = @cTask
FETCH NEXT FROM MY_data INTO @iUSCA_KEY,@iCAET_KEY,@iUSER_KEY,@iENTE_KEY,@dUSCA_DAT,@cUSCA_STA,@cUSCA_SRT,@iUserId,@cTask
END
CLOSE MY_data
DEALLOCATE MY_data
答案 1 :(得分:1)
我正在纠正中,但据我了解,循环会占用更多资源。
但是,您也可以通过循环来完成它。
请注意,由于我没有源数据和SP,因此我无法对其进行测试,但是我确定脚本是防弹的:
DECLARE @LOOP INT
, @iUSCAKEY INT
, @iCAETKEY INT
, @iUSERKEY INT
, @iENTEKEY INT
, @cUSCASTA VARCHAR(10)
, @cUSCASRT VARCHAR(10)
, @iUserId BIGINT
, @cTask VARCHAR(100)
DECLARE @TBL AS TABLE (
ID INT PRIMARY KEY IDENTITY
, iUSCA_KEY INT
, iCAET_KEY INT
, iUSER_KEY INT
, iENTE_KEY INT
, cUSCA_STA VARCHAR(10)
, cUSCA_SRT VARCHAR(10)
, iUserId BIGINT
, cTask VARCHAR(100)
)
INSERT INTO @TBL (
iUSCA_KEY
, iCAET_KEY
, iUSER_KEY
, iENTE_KEY
, cUSCA_STA
, cUSCA_SRT
, iUserId
, cTask
)
SELECT
iUSCA_KEY
, iCAET_KEY
, iUSER_KEY
, iENTE_KEY
, cUSCA_STA
, cUSCA_SRT
, iUserId
, cTask
FROM BAUSER
WHERE USER_STA = '1'
SELECT @LOOP = MIN(ID) FROM @TBL
WHILE @LOOP IS NOT NULL
BEGIN
SELECT
@iUSCAKEY = iUSCA_KEY
, @iCAETKEY = iCAET_KEY
, @iUSERKEY = iUSER_KEY
, @iENTEKEY = iENTE_KEY
, @cUSCASTA = cUSCA_STA
, @cUSCASRT = cUSCA_SRT
, @iUserId = iUserId
, @cTask = cTask
FROM @TBL
WHERE ID = @LOOP
EXEC sp_BAUSCA_BASE
@iUSCA_KEY = @iUSCAKEY
, @iCAET_KEY = @iCAETKEY
, @iUSER_KEY = @iUSERKEY
, @iENTE_KEY = @iENTEKEY
, @dUSCA_DAT = GETDATE()
, @cUSCA_STA = @cUSCASTA
, @cUSCA_SRT = @cUSCASRT
, @iUserId = @iUserId
, @cTask = @cTask
SELECT @LOOP = MIN(ID) FROM @TBL WHERE ID > @LOOP
END
让我知道它是否有效。