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?
+9
A:
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
Ardman
2010-05-27 12:35:29
A:
PostgreSQL style variables:
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;
pcent
2010-05-27 13:26:48
A:
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;
Will Marcouiller
2010-05-27 13:37:57