4

将值传递到此存储过程的正确方法是什么,显然我的做法不正确,在一个过程中执行两个语句是否安全,或者我应该创建两个单独的语句?


DELIMITER $$

    CREATE DEFINER=`root`@`localhost` PROCEDURE `drop_student`(IN section_id VARCHAR(20), IN student_id  VARCHAR(20))
    BEGIN

    SET @section_id=section_id;
    SET @student_id=student_id; 

    PREPARE STMT2 FROM 
    "DELETE FROM transcript
    WHERE STUDENT_ID = @student_id
    AND SECTION_ID = @section_id ";


    PREPARE STMT FROM 
    "DELETE FROM course
    WHERE STUDENT_ID = @student_id
    AND SECTION_ID = @section_id ";


    EXECUTE STMT2 USING @section_id,@student_id;

    EXECUTE STMT USING @section_id,@student_id;

    END
4

4 回答 4

3

你确定你在上面的代码中使用SQL Server我看到sql server标签)吗?我猜是MySQL。像这样做

PREPARE STMT2 FROM  "DELETE FROM transcript  WHERE STUDENT_ID = ? AND 
                                                   SECTION_ID = ?";
EXECUTE STMT2 USING @student_id,  @section_id;
DEALLOCATE PREPARE STMT2;

-- same as STMT

准备好的语句的 SQL 语法

于 2012-08-31T01:21:41.943 回答
1

要调用该过程,您将执行以下操作:

CALL drop_student('foo','bar');

于 2012-08-31T01:31:06.840 回答
0

你试过这样做吗?

EXEC STMT2 @section_id @student_id;

EXEC STMT @section_id @student_id;
于 2012-08-31T01:14:16.467 回答
0

您不需要在这里使用准备好的语句。实际上,您甚至可以将您的两个DELETE语句合并为一个语句:

CREATE PROCEDURE drop_student (
  IN p_section_id VARCHAR(20),
  IN p_student_id VARCHAR(20)
)
DELETE transcript, course
FROM   transcript JOIN course USING (STUDENT_ID, SECTION_ID)
WHERE  STUDENT_ID = p_student_id AND SECTION_ID = p_section_id;

此外,看起来您可能正在尝试手动实现由带有选项的外键约束自动提供的行为。ON DELETE CASCADE

于 2012-08-31T04:25:17.127 回答