SQL Server stored procedure to insert in multiple tables a [duplicate] - sql

This question already has answers here:
How to get the identity of an inserted row?
(15 answers)
Closed 5 years ago.
I have 2 tables, custlogin and custinfo:
custlogin:
custid int primary key auto notnull
custusename varchar(25)
custpassword varchar(50)
custinfo:
custid foriegnkey custlogin.custid ondelete set NULL
custfirstname varchar(25)
custlastname varchar(25)
custaddress varchar(100)
I want to write a stored procedure which will insert into both tables
More precisely, insert into custlogin with custusername custpassword, which would return custid for use as foreign key for custinfo.
I have searched much but I didn't find any solution.

If you insert 1 row to custlogin, you could use ##IDENTITY or Scope_identity() to get new inserted id.
If you insert multiple rows, then use OUTPUT to get multiple new inserted ids.
You could see an example here: http://rextester.com/TWXO81648

It will be something like below. You can use SCOPE_IDENTITY() to get the last autogenerated ID withing the scope which is this stored proc in this case:
create procedure NameOfYourProcedureHere
as
begin
insert into custlogin(custusename, custpassword)
values ('','') -- put values here (from parameters?)
insert into custinfo(custid, custfirstname, custlastname, custaddress)
values (SCOPE_IDENTITY(), '', '', '') -- put other values here (from parameters?)
end

Related

How to include a reference column with the OUTPUT in SQL [duplicate]

This question already has answers here:
Is it possible to for SQL Output clause to return a column not being inserted?
(2 answers)
Closed 11 months ago.
I have a reference TableA with a single column called [SomeID]:
SomeID
ABC
DEF
GHI
KLM
I have TableB can be:
CREATE TABLE TableB([ID] BIGINT, [Name] NVARCHAR(50))
[ID] is the primary key and is auto-increment.
I want to create a new record in TableB for each record of TableA.
So we do this:
DECLARE #OuputTable TABLE([ID] BIGINT, [SomeID] NVARCHAR(50))
INSERT INTO TableB([Name])
OUTPUT INSERTED.[ID], 'Need Associated SomeID From TableA Here' INTO #OutputTable
SELECT 'ZZZZZZ' -- Edited this line to remove some possible confusion.
FROM TableA
SELECT *
FROM
#OuputTable
How would I be able to place the associated [SomeID] value for each of the created record in #OuputTable without using a loop?
You can try to use MERGE INTO which might allow you get source data value in OUTPUT
MERGE INTO TableB AS dest
USING TableA AS sou ON 1=0
WHEN NOT MATCHED
THEN INSERT ([Name])
VALUES (sou.[SomeID])
OUTPUT INSERTED.[ID], sou.SomeID
INTO #OutputTable (ID, SomeID);
sqlfiddle

Using OUTPUT INTO with from_table_name in an INSERT statement [duplicate]

This question already has answers here:
Is it possible to for SQL Output clause to return a column not being inserted?
(2 answers)
Closed 2 years ago.
Microsoft's OUTPUT Clause documentation says that you are allowed to use from_table_name in the OUTPUT clause's column name.
There are two examples of this:
Using OUTPUT INTO with from_table_name in an UPDATE statement
Using OUTPUT INTO with from_table_name in a DELETE statement
Is it possible to also use it in an INSERT statement?
INSERT INTO T ( [Name] )
OUTPUT S.Code, inserted.Id INTO #TMP -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
Failing example using table variables
-- A table to insert into.
DECLARE #Item TABLE (
[Id] [int] IDENTITY(1,1),
[Name] varchar(100)
);
-- A table variable to store inserted Ids and related Codes
DECLARE #T TABLE (
Code varchar(10),
ItemId int
);
-- Insert some new items
WITH S ([Name], Code) AS (
SELECT 'First', 'foo'
UNION ALL SELECT 'Second', 'bar'
-- Etc.
)
INSERT INTO #Item ( [Name] )
OUTPUT S.Code, inserted.Id INTO #T -- The multi-part identifier "S.Code" could not be bound.
SELECT [Name] FROM S;
No, because an INSERT doesn't have a FROM; it has a set of values that are prepared either by the VALUES keyword, or from a query (and even though that query has a FROM, you should conceive that it's already been run and turned into a block of values by the time the insert is done; there is no s.code any more)
If you want to output something from the table that drove the insert you'll need to use a merge statement that never matches any records (so it's only inserting) instead, or perhaps insert all your data into #tmp and then insert from #tmp into the real table - #tmp will thus still be the record of rows that were inserted, it's just that it was created to drive the insert rather than as a consequence of it (caveats that it wouldn't contain calculated columns)

Select row just inserted without using IDENTITY column in SQL Server 2012

I have a bigint PK column which is NOT an identity column, because I create the number in a function using different numbers. Anyway, I am trying to save this bigint number in a parameter #InvID, then use this parameter later in the procedure.
ScopeIdentity() is not working for me, it saved Null to #InvID, I think because the column is not an identity column. Is there anyway to select the record that was just inserted by the procedure without adding an extra ID column to the table?
It would save me a lot of effort and work if there is a direct way to select this record and not adding an id column.
insert into Lab_Invoice(iID, iDate, iTotal, iIsPaid, iSource, iCreator, iShiftID, iBalanceAfter, iFileNo, iType)
values (dbo.Get_RI_ID('True'), GETDATE(),
(select FilePrice from LabSettings), 'False', #source, #user, #shiftID, #b, #fid, 'Open File Invoice');
set #invID = CAST(scope_identity() AS bigint);
P.S. dbo.Get_RI_ID('True') a function returns a bigint.
Why don't you use?
set #invId=dbo.Get_RI_ID('True');
insert into Lab_Invoice(iID,iDate,iTotal,iIsPaid,iSource,iCreator,iShiftID,iBalanceAfter,iFileNo,iType)
values(#invId,GETDATE(),(select FilePrice from LabSettings),'False',#source,#user,#shiftID,#b,#fid,'Open File Invoice');
You already know that big id value. Get it before your insert statement then use it later.
one way to get inserted statement value..it is not clear which value you are trying to get,so created some example with dummy data
create table #test
(
id int
)
declare #id table
(
id int
)
insert into #test
output inserted.id into #id
select 1
select #invID=id from #id

Confusion about Stored Procedure

I have written a stored procedure for inserting data into my table. These are my table's columns with their datatype:
Ad nvarchar(150),
Yazar nvarchar(150),
SayfaSayisi smallint,
KategoriId int
Gmc datetime,
HostName nvarchar(150)
The problem is that Gmc and HostName have their own default values. So I can't use these two in the stored procedure.
Gmc ---> GetDate() (to get insert date)
HostName --> Host_Name( )
So when I execute the query I am getting this error.
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement
This is the query
Create proc Kitap_Insert
#Ad nvarchar(150),
#Yazar nvarchar(150),
#SayfaSayisi smallint,
#KategoriId int
Gmc datetime,
HostName nvarchar(150)
as
Insert into Kitap(Id, Ad, Yazar, SayfaSayisi, KategoriId)
values(#Ad, #Yazar, #SayfaSayisi, #KategoriId)
What is the proper way of doing this?
You need remove ID from insert list
Insert into Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
values(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
or add a value for it as below
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(#ID, #Ad,#Yazar,#SayfaSayisi,#KategoriId)
Instead of :
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
Use:
INSERT INTO Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
VALUES (#Ad,#Yazar,#SayfaSayisi,#KategoriId)
You are asking SQL engine that you will provide id (an additional field) as well (field that doesn't exist in the table or is an auto increment field) and you are not providing the value for the same and hence your error here are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement
So remove additional Id from your insert query.
The error you are getting because you tried to insert value into more column names than specified in Values Clause.
If you have ID column as Auto-increment field in table so you dont have to include that ID column in so your insert query will be like this:-
Insert into Kitap
(Ad,Yazar,SayfaSayisi,KategoriId)
values
(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
If you don't have ID column as Auto-increment field in table so you provide value to that id column also in Value Clause so your insert query will be like this:-
NOTE:-
You have to calculate and Set Value to #Id variable before using it in Insert Query
Declare #Id as INT
SET #ID = ---- set here with some value which will become Primary key(I think)
Insert into Kitap
(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values
(#Id, #Ad,#Yazar,#SayfaSayisi,#KategoriId)

While inserting data to two tables using stored procedure I am getting a mismatch error

I have a table called CompanyMaster_tbl with a table structure as follows.
Cid CompanyName Deleted
and another table named DepartmentMaster_tbl,with a table structure as follows.
dtld dtname dtphone dtemail cid deleted
I've written a stored procedure for inserting data into these tables as follows.
CREATE PROCEDURE [dbo].[InsertDetails](
#companyName varchar(150),
#dname varchar(150),
#dphon varchar(150),
#deleted int,
#cid int OUTPUT
) AS
BEGIN
INSERT INTO [dbo].CompanyMaster_tbl
VALUES (#companyName)
select #cid=cid
from [dbo].CompanyMaster_tbl
WHERE ##ROWCOUNT > 0 AND cid = scope_identity()
insert into DepartmentMaster_tbl
values(#dname,
#dphon)
end
When I execute this SP, i am getting error like this:
Column name or number of supplied values does not match table definition.
try this , mention coloumn name
INSERT INTO [dbo].CompanyMaster_tbl (CompanyName )
VALUES (#companyName)
INSERT into DepartmentMaster_tbl (dname,dphon)
values(#dname, #dphon)
You are giving wrong number of values to the table i.e. you have two columns in table CompanyMaster_tbl(i think your cid is identity(auto generated) there fore i did not mention it) but you can give only one value to the table, and same thing applies for DepartmentMaster_tbl. if you can't give the values to the table then mention column names in the insert statement otherwise give all column value
e.g.
Insert into CompanyMaster_tbl(CompanyName) values(#companyName)
or
Insert into CompanyMaster_tbl values(#companyName, #deleted)