1

在动态 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

你能帮我怎么做吗?

谢谢

4

1 回答 1

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
于 2013-04-09T07:04:39.353 回答