Stored Procedure return default value? - sql

in my database, there is a Stored Procedure with INSERT INTO statement. The problem is I want this stored procedure will return the StudentCode default value, I think it's impossible to use the SELECT TOP 1 statement to get this value because there may be multiple rows inserted at the same time. Any help or suggestions?. Thanks very much
ALTER PROC [dbo].[AddStudent]
#StudentName NVARCHAR(255),
#DoB DATETIME,
#Parent NVARCHAR(255),
#ParentContact VARCHAR(16),
#Address NVARCHAR(255),
#Class VARCHAR(6),
AS
INSERT INTO dbo.Student
( StudentCode , --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class ,
)
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
-- How to return StudentCode field

Use OUTPUT INSERTED clause, as explained into official docs:-
INSERTED
Is a column prefix that specifies the value added by the
insert or update operation. Columns prefixed with INSERTED reflect the
value after the UPDATE, INSERT, or MERGE statement is completed but
before triggers are executed.
so your code is going to be like this:- (is not tested, but it guides you to accurate code)
ALTER PROC [dbo].[AddStudent]
#StudentName NVARCHAR(255),
#DoB DATETIME,
#Parent NVARCHAR(255),
#ParentContact VARCHAR(16),
#Address NVARCHAR(255),
#Class VARCHAR(6),
AS
DECLARE #StudentCodeInserted varchar(5)
INSERT INTO dbo.Student
( StudentCode, --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class
)
OUTPUT inserted.StudentCode INTO #StudentCodeInserted
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
Select #StudentCodeInserted as StudentCodeInserted

You need to Return value after INSERT
DECLARE #generated_StudentCode table(StudentCode varchar(5))
INSERT INTO dbo.Student
( StudentCode, --I set default this column
StudentName,
DateOfBirth
NameParrent ,
PhoneContact ,
AddressParent ,
Class ,
)
OUTPUT inserted.StudentCode INTO #generated_keys
VALUES ( DEFAULT , --StudentCode varchar(5)
#StudentName, --StudentName nvarchar(255)
#DoB, --DateOfBirth datetime
#Parent, --NameParrent nvarchar(255)
#ParentContact, --PhoneContact varchar(16)
#Address, --AddressParent nvarchar(255)
#Class --Class varchar(6)
)
SELECT TOP 1 * FROM #generated_StudentCode
Read the following thread to have a better understanding
SQL Server - Return value after INSERT

Related

Insert new data to a table with stored procedure

I tried to make a stored procedure the insert data to a table:
create procedure AddEmployee
(
#FirstName nvarchar(20)
, #LastName nvarchar(20)
, #BirthDate datetime
, #Country nvarchar(15)
, #City nvarchar(15)
)
as
insert into Employees
values (#FirstName, #LastName, #BirthDate, #Country, #City)
go
But when I run it I get the error message:
Msg 213, Level 16, State 1, Procedure AddEmployee, Line 2 [Batch Start Line 17]
Column name or number of supplied values does not match table definition.
I looked at this question but it didn't solve my problem:
Create a stored procedure to insert new data into a table
When using insert, always include the columns names:
create procedure AddEmployee (
#FirstName nvarchar(20) ,
#LastName nvarchar(20) ,
#BirthDate datetime,
#Country nvarchar(15),
#City nvarchar(15)
) as
begin
insert into Employees (FirstName, LastName, BirthDate, Country, City)
values (#FirstName, #LastName, #BirthDate, #Country, #City);
end;
Although SQL allows you to leave out the column names, you should include them as a best-practice. This is particularly important for those learning the language, so they learn the safer way to do things.

Declare multiple variables in SQL

I am new to SQL and trying to determine how to set a variable to either A or B.
Here is the statement:
DECLARE #Planner AS VARCHAR(50) = '2566927' OR #Planner = '12201704'
And the error I am receiving:
The following errors occurred during execution of the SQL query:
Incorrect syntax near the keyword 'OR'.
Here is a more complete sample:
DECLARE
#Planner AS VARCHAR(50) = '2566927'
--Temp Table for Final
CREATE TABLE #PP1(
Part_Key varChar(50)
,Part_No varChar(50)
,Part_Name varChar(50)
,CurInv DECIMAL(10,2)
,MinInv DECIMAL(10,2)
,Past_Due DECIMAL(10,2)
,Week2 DECIMAL(10,2)
,Week4 DECIMAL(10,2)
,Week8 DECIMAL(10,2)
,Week12 DECIMAL(10,2)
,Plus12 DECIMAL(10,2)
,Dep26w DECIMAL(10,1)
,Stock DECIMAL(10,1)
,StockPur DECIMAL (10,1)
)
--Temp Table to Limit Parts
CREATE TABLE #MRP_Parts(
MRP_PK varChar(50)
,MRP_PN varChar(50)
,MRP_PNAME varChar(50)
)
--Insert into Temp Part Table
INSERT #MRP_Parts
SELECT
PP.Part_Key
,PP.Part_No
,PP.Name
FROM Part_v_Part AS PP
WHERE (PP.Planner = #Planner OR #Planner = '')
--BEGIN Temp Table for Inventory
CREATE TABLE #CurrInv(
CI_Part_Key varChar(50)
,CI_Part_No varChar(50)
,CI_Qty DECIMAL(10,1)
,CI_Min DECIMAL(10,2)
)
INSERT #CurrInv
SELECT
PP.PArt_Key
,PP.Part_No
,ISNULL(PC1.Quantity,0)
,PP.Minimum_Inventory_Quantity
FROM Part_v_Part AS PP
OUTER APPLY
(
SELECT
SUM(PC.Quantity) AS Quantity
FROM Part_v_Container as PC
WHERE PP.part_Key=PC.part_Key
AND (PC.Container_Status = 'OK'
OR PC.Container_Status = 'Receiving'
OR PC.Container_Status = 'Testing Hold')
AND PC.Active = '1'
AND (PP.Planner = #Planner OR #Planner = '')
) AS PC1
What I would like is for the #Planner to be either A or B
A second variable must have a different name. E.g.
DECLARE #Planner1 VARCHAR(50) = '2566927',
#Planner2 varchar(10) = '12201704',
#OtherVar int = 42
And separate each variable declaration with a comma ,
You can't do that, but you can declare a variable as a table and put multiple values into the table
DECLARE #Planner AS TABLE (P VARCHAR(50))
INSERT #Planner SELECT '2566927'
INSERT #Planner SELECT '12201704'
And then you can use the table variable in a where in type clause
SELECT
PP.Part_Key
,PP.Part_No
,PP.Name
FROM Part_v_Part AS PP
WHERE PP.Planner IN (SELECT P FROM #Planner)

SQL Server Stored Procedure - Return varchar id of inserted row

I'm working on a cascading insertion where a stored procedure should return an id of the inserted row. This would not be a problem if the id of the table was an int. However, the id is a varchar and therefore I cannot use SCOPE_IDENTITY().
This is my procedure so far:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
INSERT INTO nextlabel.[Article] (name, article_nr, category, container_id, count_per_container, picture_id )
VALUES (#name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
SET #id = SCOPE_IDENTITY()
Where the last row is not correct since the column id is a varchar.
How can I return the id?
Try this:
CREATE PROCEDURE NEW_ARTICLE
#id varchar(50) OUTPUT,
#name varchar(100),
#articleNr varchar(50),
#gategory varchar(50),
#containerId varchar(50),
#contPerContainer int,
#pictureId varchar(50)
AS
SET NOCOUNT OFF
SET #id = newid()
INSERT INTO nextlabel.[Article] (id, name, article_nr, category, container_id, count_per_container, picture_id)
VALUES (#id, #name, #articleNr, #gategory, #containerId, #contPerContainer, #pictureId)
GO

How to map table fields from source as the variables of stored procedure in destination in SSIS Package?

I want to transfer data from source Database table named Patient (which contains many rows) to destination database tables(2) named Person & Patient.
I already have stored procedure named AddPatient in destination database which will add person related fields to Person table and other fields to Patient table, so I would like to execute that procedure and to assign the fields from source database as variables to it. The following are the code of AddPatient sp in destination database.
ALTER PROCEDURE [dbo].[AddPatient]
(
#TenantId BIGINT,
#FirstName NVARCHAR(100),
#LastName NVARCHAR(100),
#PersonNumber NVARCHAR(20),
#MobileNumber NVARCHAR(20),
#EmailId NVARCHAR(100),
#Address NVARCHAR(255),
#City NVARCHAR(50),
#ZipCode NVARCHAR(20),
#ListComments NVARCHAR(1000),
#Comment NVARCHAR(500),
#AlternateEmailId NVARCHAR(100) ,
#HomePhone NVARCHAR(20) ,
#Relative NVARCHAR(255) ,
#HasDiabetes [bit],
#HasBlooPressure [bit],
#AddedBy BIGINT,
#AddedDateTime smalldatetime,
#PersonId BIGINT OUTPUT
)
AS
BEGIN
SET NOCOUNT ON
IF #TenantId IS NULL
RAISERROR('The value for #TenantID should not be null', 15, 1) -- with log
ELSE
BEGIN
DECLARE #new_person_id BIGINT
DECLARE #new_patient_id BIGINT
DECLARE #PatientIdentifier NVARCHAR(50)
EXEC dbo.GetNextPatientIdForTenant #TenantID, #PatientIdentifier OUTPUT
INSERT INTO dbo.Person
(
TenantId,
FirstName,
LastName,
PersonNumber,
MobileNumber,
EmailId,
Address,
City,
ZipCode,
AddedBy,
AddedDateTime
)
VALUES
(
#TenantId,
#FirstName,
#LastName,
#PersonNumber,
#MobileNumber,
#EmailId,
#Address,
#City,
#ZipCode,
#AddedBy,
#AddedDateTime
)
SELECT #new_person_id = SCOPE_IDENTITY()
INSERT INTO dbo.Patient
(
TenantId,
PatientIdentifier,
PersonId,
ListComments,
Comment,
AlternateEmailId,
HomePhone,
Relative,
HasDiabetes,
HasBlooPressure,
AddedBy,
AddedDateTime
)
VALUES
(
#TenantId,
#PatientIdentifier,
#new_person_id,
#ListComments ,
#Comment ,
#AlternateEmailId,
#HomePhone ,
#Relative ,
#HasDiabetes,
#HasBlooPressure,
#AddedBy ,
#AddedDateTime
)
SELECT #new_patient_id = SCOPE_IDENTITY()
SELECT #PersonId = #new_person_id
SELECT #new_patient_id
END
END
There is no TenantId & AddedBy field in source, so I want to assign both as 1 for all rows to be transfered.
I know Execute SQL Task will handles stored procedure and for each row data Foreach Loop Container will take care in SSIS. But I don't know how to assign the variables of sp in destination database to the fields of table from source database.
Anyone help me with this.
Thanks in advance !

How to have multiple inserts in one sql query that uses the identities from the previous table

I am trying to insert data into many tables in one SQL Server stored procedure. I am also using the identities from the tables that I have inserted data into to then resolve the many to many relationship by writing those identities to another table.
In theory the logic seems to be there for the stored procedure, but on execution only the first insert statement has been executed. Please could anyone assist with this.
The stored procedure is as follows:
Create Procedure [dbo].[InsertAllCustomerDetails]
(
--#CustomerID Bigint output,
#Firstname varchar(100),
#LastName varchar(100),
#Initials varchar(10),
#Title varchar(20),
#DateCreated datetime,
#isDeleted Bit,
--#ContactNumberID BIGINT Output,
#ContactNumber Varchar(100),
#ContactTypeID bigint,
#Street Varchar(550),
#AreaID BIGINT,
#isPreferred Bit
--#AddressID Bigint OutPut
)
AS
Insert Into Customer
(
FisrtName,
LastName,
Initials,
[Title],
DateCreated,
isDeleted
)
Values
(
#Firstname,
#LastName,
#Initials,
#Title,
#DateCreated,
#isDeleted
)
Declare #CustomerID BIGINT
SELECT #CustomerID = ##IDENTITY
RETURN #CustomerID
--This will now insert the contact details for the customer
Insert Into ContactNumber
(
ContactNumber,
ContactTypeID
)
Values
(
#ContactNumber,
#ContactTypeID
)
Declare #ContactNumberID BIGINT
SELECT #ContactNumberID = ##IDENTITY
--This will insert into the CustomerContactNumber
Insert Into CustomerContactNumber
(
ContactNumberID,
CustomerID
)
Values
(
#ContactNumberID,
#CustomerID
)
--This will insert the address
Insert Into [Address]
(
Street,
AreaID,
isPreferred
)
Values
(
#Street,
#AreaID,
#isPreferred
)
Declare #AddressID BIGINT
SELECT #AddressID = ##IDENTITY
--This will insert the relationship for the customer Address table
Insert into CustomerAddress
(
CustomerID,
AddressID
)
Values
(
#CustomerID,
#AddressID
)
I see two things:
You seem to have a typo in the Customer insert:
Insert Into Customer
(
FisrtName, <-- should be FirstName?
LastName,
You are RETURNing after the Customer insert - that's why only the first one runs
Declare #CustomerID BIGINT
SELECT #CustomerID = ##IDENTITY
RETURN #CustomerID <---- This exits the sproc
--This will now insert the contact details for the customer
Insert Into ContactNumber
I'm guessing the RETURN was there for debugging and not removed since it's obscured by the indentation.