在动态SQL语句中,一个@STU_ID值无法将数据插入另一个表中。在这里,我需要知道哪个@STU_ID在执行时失败。
CREATE PROC DATA_COPY
(
@SRC_TABLE VARCHAR(30),
@DEST_TABLE VARCHAR(30)
)
AS
DECLARE @STU_ID INT
BEGIN
DECLARE STUDENT_CURSOR CURSOR FOR
SELECT DISTINCT STU_ID FROM STUDENT
OPEN STUDENT_CURSOR
FETCH NEXT FROM STUDENT_CURSOR INTO @STU_ID
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ('INSERT INTO '+@DEST_TABLE+'
SELECT *
FROM '+@SRC_TABLE+'
WHERE STU_ID='+@STU_ID)
FETCH NEXT FROM STUDENT_CURSOR INTO @STU_ID
END
CLOSE STUDENT_CURSOR
DEALLOCATE STUDENT_CURSOR
END
你能帮我解决这个问题吗?
由于
答案 0 :(得分:1)
您可以使用TRY CATCH
在错误上下文中捕获数据BEGIN TRY
EXEC ('INSERT INTO '+@DEST_TABLE+'
SELECT *
FROM '+@SRC_TABLE+'
WHERE STU_ID='+@STU_ID)
END TRY
BEGIN CATCH
PRINT 'ERROR WITH VALUE @STU_ID = ' + CONVERT(VARCHAR,@STU_ID)
END CATCH