How to insert a dynamic sql variable into a temporary table - sql

So I want to insert the variables email, username, and age from a stored procedure into a temporary table and am running into a few issues.
Declare #email [varchar](8000)
,#user_name [varchar](8000)
, age[int]
select distinct value as value
into #temptable
from #email
,#user_name
,#age
select *
from #temptable
I am getting a syntax error. Does anybody have any advice?

Generally, I would use this syntax to insert the results of a stored procedure into a table or table variable:
INSERT #temptable EXECUTE dbo.MyStoredProcedureName
For example (table variable example):
declare #temptable table
(
name varchar(255),
field varchar(255),
filename varchar(255),
filegroup varchar(255),
size varchar(255),
maxsize varchar(255),
growth varchar(255),
usage varchar(255)
);
INSERT #temptable Exec sp_helpfile;
select * from #temptable ;
EDIT: Per your question about why can't you do this in the SP itself, the syntax would be something like:
DECLARE #Email nvarchar(4000),#UserName nvarchar(4000),#age int
declare #temptable table
(
email nvarchar(4000),
UserName nvarchar(4000),
age int
)
SELECT #Email = 'test#test.com', #UserName = 'MyName', #age = 21
INSERT INTO #temptable(Email, UserName, age) SELECT #Email, #UserName, #age
SELECT * FROM #temptable

Related

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)

Return inserted row from stored procedure

I have the following stored procedure
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
SELECT #new_identity = SCOPE_IDENTITY()
SELECT * FROM NameAge where Id = #new_identity
Is there are a more efficient way to return the last inserted record complete with id and associated data?
Use Insertedwithin output clause,
As the follwoing:
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
AS
DECLARE #MyTableVar table(
Name varchar(50),
Identifier uniqueidentifier
;
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
OUTPUT INSERTED.Name, INSERTED.Identifier
INTO #MyTableVar
SELECt Name,Identifier from #MyTableVar
Refreance:
Best way to get identity of inserted row?
SCOPE_IDENTITY() is used to get the last generated Identity value in an identity column in your scope , For GUID values either you get the guid before you insert it like I have done in the code below , or you use OUTPUT clause to get the guid generated by the Insert statement.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128)
AS
BEGIN
SET NOCOUNT ON;
Declare #NewID UNIQUEIDENTIFIER = NEWID();
insert into NameIdentifier ( Name, Identifier)
values( #name, #NewID);
SELECT * FROM NameAge where Id = #NewID;
END
This should give you your desired functionality.
CREATE PROCEDURE [dbo].[spInsert]
#name nvarchar(128),
#Ret int Output
AS
BEGIN
insert into NameIdentifier
( Name, Identifier)
values
( #name, NEWID());
END
SET #Ret = ##IDENTITY
EDIT: This will return the id of your newly inserted row.
You can achieve this by using the output clause of SQL Server, you can read more about this here
if exists (select 1 from sys.tables where name = 'NameIdentifier ')
drop table NameIdentifier
create table NameIdentifier
(
id BIGINT IDENTITY(1,1)
,Name VARCHAR(100)
,Identifier uniqueidentifier
)
DECLARE #id TABLE
(
ID BIGINT
)
INSERT INTO NameIdentifier (Name,Identifier)
OUTPUT INSERTED.id INTO #id
VALUES('abcd',NEWID())
SELECT * FROM NameIdentifier N, #id I where N.id = I.id

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 can I insert the results of a stored procedure into a new table

ALTER procedure [dbo].[staffscorecard]
#STAFF_ID INT = NULL
as
select
count(STAFF_ID) as countexel
from
TbStudentSurvey
where
FEEDBACK = 'excellent'
and STAFF_ID = ISNULL(#STAFF_ID, STAFF_ID)
select
Score as scoreexel
from
TbStaffScoreMaster
where
Status = 'Excellent'
exec [dbo].[staffscorecard]
GO
CREATE TABLE #temp ( countexel int, scoreexel int)
GO
INSERT INTO #temp (countexel , scoreexel)
EXEC [dbo].[staffscorecard]
GO
SELECT *
FROM #temp
GO
For a given staffid to calculate countexel and scoreexel you can re-write your stored procedure as:
create table TbStudentSurvey (STAFF_ID int,FEEDBACK varchar(20));
insert into TbStudentSurvey values (1,'excellent'),(1,'excellent'),(2,'excellent');
create table TbStaffScoreMaster (Score int,[Status] varchar(20));
insert into TbStaffScoreMaster values(100,'Excellent');
Go
create procedure [dbo].[staffscorecard]
#STAFF_ID INT = NULL,
#countexel int output,-- Explicitly declare output variables to fetch these values
#scoreexel int output
as
Begin
select
#countexel = count(STAFF_ID)
from
TbStudentSurvey
where
FEEDBACK = 'excellent'
and STAFF_ID = ISNULL(#STAFF_ID, STAFF_ID)
select
#scoreexel = Score
from
TbStaffScoreMaster
where
Status = 'Excellent'
End
GO
and then instead of using a temp table use a table variable because when you use temp tables,the table has to match the exact column layout as of the stored procedure.
--CREATE TABLE #temp (countexel int, scoreexel int)
--GO
--Create a table variable:
declare #temp table (countexel int, scoreexel int)
declare #countexel int, #scoreexel int,#STAFF_ID int;
--set value of staff Id for which you want to get countexel and scoreexel.
set #STAFF_ID = 1;
EXEC [dbo].[staffscorecard] #STAFF_ID ,#countexel output,#scoreexel output
INSERT #temp values (#countexel ,#scoreexel);
SELECT *
FROM #temp
GO
Method 2:
You can also write as:
alter procedure [dbo].[staffscorecard]
#STAFF_ID INT = NULL
as
Begin
select
count(STAFF_ID) as countexel , Score as scoreexel
from
TbStudentSurvey TSS
inner join TbStaffScoreMaster TSM on TSM.Status = TSS.FEEDBACK
where
FEEDBACK = 'excellent'
and STAFF_ID = ISNULL(#STAFF_ID, STAFF_ID)
group by STAFF_ID,Score
End
GO
declare #temp table (countexel int, scoreexel int)
declare #STAFF_ID int;
set #STAFF_ID = 1;--set value of staff Id for which you want to get countexel and scoreexel.
INSERT #temp EXEC [dbo].[staffscorecard] #STAFF_ID
SELECT *
FROM #temp
GO
Hope this helps!!

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.