I working in .Net Application. Here in my aspx page, i am having 3 Tabs (i.e) Tab 1, Tab 2,Tab 3. The first Tab contains some Textbox controls, the Second tab contains some combo box controls and same as Third tab contains some controls. I want to save all these three tab controls to THREE different tables in SQL Database. Only one Stored Procedure should be used for this. The PRIMARY KEY of the FIRST table should be saved in the SECOND and THIRD table. ( LIKE, REFERENTIAL INSERT ). Here is my SP…
ALTER PROCEDURE [dbo].[Insert]
(@Name NVARCHAR(50))
AS
BEGIN
SET NOCOUNT ON
DECLARE @TableOnePrimaryKey INT
BEGIN
INSERT INTO TABLEONE(Name)
VALUES (@Name)
SELECT @TableOnePrimaryKey=@@IDENTITY
SELECT CAST(@@IDENTITY AS INT)
INSERT INTO TABLETWO(TableTwoIDColumn)
VALUES (@TableOnePrimaryKey)
SELECT @TableOnePrimaryKey=@@IDENTITY
SELECT CAST(@@IDENTITY AS INT)
INSERT INTO TABLETHREE(TableThreeIDColumn)
VALUES (@TableOnePrimaryKey)
SELECT @TableOnePrimaryKey=@@IDENTITY
SELECT CAST(@@IDENTITY AS INT)
INSERT INTO TABLEFOUR(TableFourIDColumn)
VALUES (@TableOnePrimaryKey)
END
But, its the TABLE ONE Primary key is not got saved in other tables. How to Fix this..
Use
scope_identity()instead of@@identity. And you should not assign the value to@TableOnePrimaryKeymore than once. If you have an identity column in the other tables you loose the identity you got from the first insert.