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)
Related
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
DECLARE #sql1 NVARCHAR(MAX),
#sql2 NVARCHAR(MAX);
Let's create a temp table named #Table1 to put output from first dynamic query
CREATE TABLE #Table1
(
[CustomerID] varchar(20) NULL,
[CustomerName] varchar(20) NULL,
[DColumn01] char(1) NULL,
[DColumn02] char(1) NULL,
[DColumn03] char(1) NULL,
[DColumn04] char(1) NULL
-- .....
-- .....
[DColumn10] char(1) NULL
);
Let's create a temp table named #Table2 to put output from second dynamic query
CREATE TABLE #Table2
(
[CustomerID] varchar(20) NULL,
[CustomerName] varchar(20) NULL,
[PColumn01] char(1) NULL,
[PColumn02] char(1) NULL,
[PColumn03] char(1) NULL,
[PColumn04] char(1) NULL
-- .....
-- .....
[PColumn10] char(1) NULL
-- .....
-- .....
[PColumn20] char(1) NULL
);
Based on some condition first dynamic query select output look like below select query from #Table1:
SET #sql1 = N'SELECT [CustomerID], [CustomerName], [DColumn01], [DColumn02], [DColumn03], [DColumn04], [DColumn10] FROM #Table1';
EXECUTE sp_executesql #sql1;
Here select column can vary based on other dynamic condition. Here column name can vary from "01" to "10" for DColumn like [DColumn09]
Based on some condition second dynamic query select output look like below select query from #Table2
SET #sql2 = N'SELECT [CustomerID], [CustomerName], [PColumn01], [PColumn02], [PColumn03], [PColumn04], [PColumn10], [PColumn20] FROM #Table2';
EXECUTE sp_executesql #sql2;
Here select column can vary based on other dynamic condition. Here column name can vary from "01" to "20" for PColumn like [PColumn15].
Now I need to join both dynamic query based on [CustomerID].
[CustomerID], [CustomerName], [DColumn01], [DColumn02], [DColumn03], [DColumn04], ....., [DColumn10], [PColumn01], [PColumn02], [PColumn03], [PColumn04], ....., [PColumn10], ....., [PColumn20]
AS the select query can vary based on column name, so I am not able to insert into any temp table.
My thought:
SET #sql1 = N'SELECT [CustomerID], [CustomerName], [DColumn01], [DColumn02], [DColumn03], [DColumn04], [DColumn10]
INTO #abc
FROM #Table1;
SELECT [CustomerID] AS [PCustomerID], [CustomerName] AS [PCustomerName], [PColumn01], [PColumn02], [PColumn03], [PColumn04], [PColumn10], [PColumn20]
INTO #xyz
FROM #Table2;
SELECT t1.*, t2.*
FROM #Table1 AS t1
INNER JOIN #Table2 AS t2 ON t1.[CustomerID] = t2.[CustomerID]';
EXECUTE sp_executesql #sql1;
DROP TABLE #Table1;
DROP TABLE #Table2;
How can i join that two dynamic SQL result set and get output where column name is not predefined? I tried to do one way, but not sure is there any better way to do that
database diagram
For sql-server
How can I insert a SKU row into table SKU_DATA, then insert the SKU into INVENTORY table with all branches and Quantity on hand=2 and Quantityonhand=0.
I need to insert a SKU item into SKUDATA and correspond row in inventory table for all existing branches Quantityonhand=2 and Quantityonhand = 0.
Please help Thanks
BRANCH
name varchar (30) not NULL,
managerNum INT NOT NULL,
SKU_DATA
SKU Int NOT NULL IDENTITY (1000,1),
description varchar (40) NOT NULL UNIQUE,
department varchar(30) NOT NULL default 'Home Entertainment',
sellingPrice numeric (7,2) NOT NULL ,
INVENTORY
SKU Int NOT NULL,
branch varchar (30) NOT NULL ,
quantityOnHand Int NOT NUll ,
quantityOnOrder Int NOT NUll ,
Procedure:
Create procedure InsertNewSkuWithInventory
#description varchar (40),
#department varchar(30),
#sellingPrice numeric (7,2),
AS
Declare #rowcount as int
Declare #SKU as int
Declare #branch as varchar(30)
Select #rowcount = COUNT(*)
from dbo.SKU_DATA
Where description = #description
And department = #department
And sellingPrice = #sellingPrice;
BEGIN
INSERT INTO dbo.SKU_DATA (description, department, sellingPrice)
VALUES (#description, #department, #sellingPrice);
Select #SKU =SKU
From dbo.SKU_DATA
Where description = #description
And department = #department
And sellingPrice = #sellingPrice;
DECLARE SKUCursor CURSOR FOR
SET #branch = ##IDENTITY
Select SKU
From dbo.inventory
Where
CLOSE SKUCursor
DEALLOCATE SKUCursor
END
There are two problems here: first, how to get the generated IDENTITY value for the newly inserted row into SKU_DATA table, and second, how to one row into INVENTORY table for each branch.
If you're inserting only a single row into SKU_DATA, then use the scope_identity() function (never use the ##IDENTITY!). Like this:
INSERT INTO dbo.SKU_DATA (description, department, sellingPrice)
VALUES (#description, #department, #sellingPrice);
set #SKU = scope_identity()
Then you do insert into INVENTORY by selecting from BRANCH table:
insert dbo.INVENTORY (SKU, branch, quantityOnHand, quantityOnOrder)
select #SKU, b.name, 2, 0
from dbo.Branch b
Hope you can work the complete solution out from this.
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!!
I have a table valued function as below. When I am trying to pass more than one parameter at the same time I am getting a error like "Function has too many arguments specified" .
CREATE FUNCTION [dbo].[GetCompanyUsers](#CompanyId BIGINT)
RETURNS #Users TABLE (Id BIGINT,Contact NVarchar(4000))
AS
BEGIN
INSERT INTO #Users(Id,Contact)
SELECT [Id]
,ISNULL([FirstName],'')+' ' +ISNULL([LastName],'') AS [Contact]
FROM [dbo].[CompanyAddressesContacts]
WHERE [CompanyId]=#CompanyId
ORDER BY ISNULL([FirstName],'')+' ' +ISNULL([LastName],'')
RETURN
END
What modifications I require in the above code so that it allows multiple values and I need to use the function in a "WHERE" condition in my dataset.
WHERE(Document_RFIs.CreatedBy IN
(SELECT Id FROM dbo.GetCompanyUsers(#CompanyId)))
This may help (but the fundamental problem is - passing a comma delimited string is something to be avoided unless absolutely necessary - which explains why you have received so few answers):-
--set nocount on
--create table #Document_RFIs (
-- CreatedBy varchar(50),
-- columna varchar(50),
-- columnb varchar(50),
-- columnc varchar(50)
--)
--insert into #Document_RFIs values
-- ('albert einstein','another','value',null),
-- ('marie curie','some',null,'tuna'),
-- ('isaac newton','why','not','provide'),
-- ('kepler','some','test','data'),
-- ('robert boyle','with','your','question'),
-- ('john dalton','it',null,'would'),
-- ('enrico fermi','make','helping','you'),
-- ('peter higgs','so','much','easier')
--create table #CompanyAddressesContacts (
-- companyid int,
-- firstname varchar(50),
-- lastname varchar(50)
--)
--insert into #CompanyAddressesContacts values (22,'albert','einstein')
--insert into #CompanyAddressesContacts values (23,'marie','curie')
--insert into #CompanyAddressesContacts values (23,'isaac','newton')
--insert into #CompanyAddressesContacts values (24,null,'kepler')
--insert into #CompanyAddressesContacts values (25,'robert','boyle')
--insert into #CompanyAddressesContacts values (25,'enrico','fermi')
--insert into #CompanyAddressesContacts values (26,'peter','higgs')
declare #ids varchar(1024)
set #ids='23,24,25'
create table #id (
companyid int
)
declare #pos int
while DATALENGTH(#ids)>0 begin
set #pos=charindex(',',#ids)
if #pos>0 begin
insert into #id values (left(#ids,#pos-1))
set #ids=SUBSTRING(#ids,#pos+1,DATALENGTH(#ids))
end else begin
insert into #id values (#ids)
set #ids=''
end
end
select d.*
from #Document_RFIs d
where exists(
select cac.*
from #CompanyAddressesContacts cac
join #id i on i.companyid=cac.companyid
where isnull(cac.firstname+' ','')+isnull(cac.lastname,'')=d.CreatedBy
)
--drop table #id
--drop table #Document_RFIs
--drop table #CompanyAddressesContacts
I would do something like this:
First convert your #CompanyId to rows
WITH CompanyIds AS (
SELECT Id
FROM CompanyTable -- Same as the source of the #CompanyId
WHERE Id IN (#CompanyId)
)
Then extract all users
,Users AS (
SELECT UserId
FROM CompanyIds
CROSS APPLY (
SELECT Id AS UserId
FROM dbo.GetCompanyUsers(CompanyIds.Id)
) AS CA1
)
And then use it in the where statement
WHERE Document_RFIs.CreatedBy IN (SELECT UserId
FROM Users)