SQL 如何在存储过程中使用局部变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2921074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:22:36  来源:igfitidea点击:

How to use local variables in stored procedures?

sqlsql-serverstored-proceduresvariables

提问by ram

if I want to select any id from a table and want to insert it's value in another table as foreign key then how i will do it through stored procedure?

如果我想从表中选择任何 id 并想将它的值作为外键插入另一个表中,那么我将如何通过存储过程来做到这一点?

回答by Neil Knight

An example of how I would approach this.

我将如何处理这个问题的一个例子。

DECLARE @MyID INT;

SET @MyID = 0;

SELECT @MyID = [TableID]
  FROM [MyTable]
 WHERE [TableID] = 99;

IF @MyID > 0
BEGIN

    INSERT INTO [MySecondTable]
         VALUES (@MyID, othervalues);

END

回答by pcent

PostgreSQL style variables:

PostgreSQL 样式变量:

DECLARE my_variable1 int;
DECLARE my_variable2 int;
BEGIN
  my_variable1 := 25;
  SELECT INTO my_variable2 id FROM my_table1;
  INSERT INTO my_table2 (my_field1, my_field2, id) VALUES ('XXX', 'YYY', my_variable2);
END;

回答by Will Marcouiller

Oracle style variables:

Oracle 样式变量:

DECLARE v_MyVariable1 NUMBER;
DECLARE v_MyVariable2 VARCHAR2(100);

BEGIN
    v_MyVariable1 := 0;
    SELECT INTO v_MyVariable2 CUSTOMER_NAME
        FROM CUSTOMERS;

    SELECT INTO v_MyVariable1 CUSTOMER_HISTORY_SEQ.NEXTVAL FROM DUAL;

    INSERT INTO CUSTOMERS_HISTORY (CUSTOMER_ID, CUSTOMER_NAME) VALUES (v_MyVariable1, v_MyVariable2);

    EXCEPTION
        WHEN OTHERS THEN
            NULL;
END;