After you do the insert into table 1
INSERT INTO Table1 (<ColumnList>) VALUES(<ValueList>)
You can capture the newly created Identity value by doing the following
SET @Variable = Scope_Identity()
You would then use this value for the ID column when you insert the row in Table2.
The SET statement captures the identity created when data was inserted in table 1.
That is the value to use in Table2.ID.
DECLARE
@Variable <datatype of ID column>
INSERT
INTO Table1 (<ColumnList>) VALUES(<ValueList>)SET
@Variable = Scope_Identity()
INSERT
INTO Table2 (ID, <remaining ColumnList>) VALUES(@Variable, <remaining values>)
If you want to do it in a trigger, there is a different method to use.
You would put the trigger on table1. Inside that insert trigger, you would use the virtual table named inserted which will contain a row for each row just inserted into table1, including the newly generated identity value for each row.
If you post your table create staements, and a descripttion of what you want to do, we can likely help you in writing the trigger.
IF
OBJECT_ID ('dbo.Table1InsertTrigger', 'TR') IS NOT NULL DROP TRIGGER dbo.Table1InsertTriggerGO
CREATE
TRIGGER dbo.Table1InsertTriggerON
dbo.Table1AFTER
INSERTIF ( @@ROWCOUNT = 0 ) RETURN INSERT INTO Table2 (ID, <remaining ColumnList>) SELECT ID, <remaining ColumnList> FROM INSERTED
GO
(Unless I am confused, which does happen) What you are wanting to do doesn't really make sense in SQL Server storage. To do this, you would be creating partial rows. It would likely be a bad practice to automatically create a row with null values that might just end up as a useless row.
What you are describing sounds more of a task that might be done in a user interface, in order to display a new row for a person to edit. If you want to create a row in T1 and T2 simultaneously, you could use a stored procedure and build the rows together in the context of a transaction.
Here ya go.
But like Louis, I wonder why you're creating a placeholder. I would think the application would have the ID of the associated T1 entry when the user is working on the T2 entry.
CREATE
TABLE [T1] ([ID]
int IDENTITY(1000, 2) NOT NULL,[NAME]
VARCHAR(100),[SERV_TYPE]
VARCHAR(40),[NWT]
VARCHAR(40),[ROWVERSION]
TIMESTAMP,CONSTRAINT
[T1_ID] PRIMARY KEY ([ID]))
GO
CREATE
TABLE [T2] ([ID]
INT NOT NULL,[CONTACT_TYPE]
VARCHAR(1),[CONTACT_NAME]
VARCHAR(40),[CONTACT_1]
VARCHAR(100),[CONTACT_2]
VARCHAR(50),[ROWVERSION]
TIMESTAMP,CONSTRAINT
[PK_T2] PRIMARY KEY ([ID]))
GO
ALTER
TABLE [T2] ADD CONSTRAINT [T1_T2]FOREIGN
KEY ([ID]) REFERENCES [T1] ([ID])GO
IF
OBJECT_ID ('dbo.Table1InsertTrigger', 'TR') IS NOT NULLDROP
TRIGGER dbo.Table1InsertTriggerGO
CREATE
TRIGGER dbo.Table1InsertTriggerON
dbo.T1AFTER
INSERTAS
IF ( @@ROWCOUNT = 0 ) RETURN INSERT INTO T2 (ID) SELECT ID FROM INSERTEDGO
insert
into t1( [NAME] , [SERV_TYPE], [NWT] )values
('Name1', 'Service1', 'what is nwt ')select
* from t1select
* from t2