-3

This is SQL code:

Declare @A_ID  AS A_ID

insert into TBL_FO VALUES(NEWID(), @A_ID, '30000.00','1','1')
(select * from TBL_DETAIL where A_ID = '59366409-2EB6-49BC-A88F-801692B735D6')
  1. I want to follow or copy the A_ID from TBL_DETAIL as '59366409-2EB6-49BC-A88F-801692B735D6' to TBL_FO for @A_ID.. How I can declare the A_ID for copy the same ID
KH LIM
  • 93
  • 1
  • 12
  • 2
    Can you share please share the structures of `tbl_fo` and `tbl_detail`? – Mureinik Jul 31 '16 at 07:06
  • 1
    Which RDBMS is this for? Please add a tag to specify whether you're using `mysql`, `postgresql`, `sql-server`, `oracle` or `db2` - or something else entirely. – marc_s Jul 31 '16 at 07:08
  • 3
    added `tsql` and `sql-server` tags based on the syntax used –  Jul 31 '16 at 07:09
  • Noted and thank you guys. – KH LIM Jul 31 '16 at 07:29
  • Possible duplicate of [How can I insert values into a table, using a subquery with more than one result?](http://stackoverflow.com/questions/9692319/how-can-i-insert-values-into-a-table-using-a-subquery-with-more-than-one-result) – AlexB Jul 31 '16 at 07:39
  • 1
    Tip: You can use an [`OUTPUT`](https://msdn.microsoft.com/en-us/library/ms177564.aspx) clause to get any data from the rows (Note plural.), e.g. identity column values for newly inserted rows. `OUTPUT` can be used with `INSERT`, `UPDATE`, `DELETE` and `MERGE` and provides access to both _before_ and _after_ values in the case of `UPDATE`. A tool well worth having in your pocket. – HABO Jul 31 '16 at 13:38

2 Answers2

1

Try this:

Declare @A_ID  as varchar(100) -- adjust the length as needed
select @A_ID = A_ID from TBL_DETAIL where A_ID = '59366409-2EB6-49BC-A88F-801692B735D6'

Declare @FO_ID as int -- To insert this into One or more tables
SET @FO_ID = NEWID() -- Initialize it one time.

insert into TBL_FO VALUES(@FO_ID, @A_ID, '30000.00','1','1') -- First use of @FO_ID

insert into TBL_SOMEOTHERTBL VALUES( @FO_ID, .... )  -- Second use of @FO_ID

etc ...
objectNotFound
  • 1,683
  • 2
  • 18
  • 25
1

Specify the columns you want to set and then follow with the subquery having the values you need in addition to the A_ID(in the order of your column names) :

insert 
into 
   TBL_FO (FirstColumnName, 
           SecondColumnName, 
           ThirdColumnName, 
           FourthColumnName, 
           FifthColumnName) 
(select 
   NEWID(), 
   A_ID, 
   '30000.00', 
   '1', 
   '1' 
 from 
   TBL_DETAIL 
 where 
   A_ID = '59366409-2EB6-49BC-A88F-801692B735D6')

Note: there is also the option to not specify the column names if the table columns are in the same order as you insert them

AlexB
  • 3,518
  • 4
  • 29
  • 46