如何在存储过程中使用本地变量?

时间:2022-09-11 17:04:56

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并将它的值作为外键插入到另一个表中,那么我如何通过存储过程来实现它呢?

3 个解决方案

#1


18  

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

#2


0  

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;

#3


0  

Oracle style variables:

甲骨文风格变量:

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;

#1


18  

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

#2


0  

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;

#3


0  

Oracle style variables:

甲骨文风格变量:

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;