SQL Server : use bigint variable in stored procedure - sql

Very simply, I am calling a procedure to get the primary key from one table, then storing the key in a variable so that I can then use it to insert into another table that needs a foreign key. The variable is what I expect it to be, however when I use it it returns nothing.
After trying looking at it, it appears to be that its an issue with the WHERE clause and using the variable
DECLARE #ClientId bigint;
SELECT *
FROM Testing.dbo.Client
WHERE ClientID = #ClientId
#ClientId value is 2
There is a value of 2 for a as a client ID in the table
When I run this I get the result I expect
select *
from Testing.dbo.Client
where ClientID = 2
This is where it gets set
DECLARE #ClientId int;
EXECUTE #ClientId = Testing.dbo.GetClientID #ClientName;
Where GetClientID is the following
USE Testing
GO
CREATE PROCEDURE GetClientId
#ClientName nvarchar(50)
AS
SELECT ClientID FROM Testing.dbo.Client WHERE ClientName = #ClientName
GO
Worked out a bit more now, so the ClientId is not getting set after call to the proc

You need to initalize variable otherwise it contains NULL;
DECLARE #ClientId bigint = 2;
select * from Testing.dbo.Client where ClientID = #ClientId;
If you have it in argument list don't create variable with this name:
CREATE PROC stored_procedure
#ClientID BIGING
AS
BEGIN
select * from Testing.dbo.Client where ClientID = #ClientId;
END

If are you trying to set a variable with a store procedure this is the right way:
DECLARE #ClientId Table(ClientId int);
Insert Into #ClientId(ClientId)
Exec Testing.dbo.GetClientID #ClientName;
select *
from Testing.dbo.Client
where ClientID = (Select ClientId From #ClientId);
If your store procedure throws many rows change the = for In like this:
select *
from Testing.dbo.Client
where ClientID in (Select ClientId From #ClientId);

I managed to work it out using OUTPUT variables which i had not come across before
USE Testing
GO
CREATE PROCEDURE AddReading
#ClientName NVARCHAR(50),
#MonitorName NVARCHAR(50),
#DateTime DATETIME,
#Temperature DECIMAL(12, 10),
#Humidity DECIMAL (12, 10),
#Staleness DECIMAL (12, 10)
AS
DECLARE #ClientId int;
EXEC Testing.dbo.GetClientId #ClientName, #ClientId OUTPUT;
INSERT INTO Testing.dbo.Reading
(ClientID, MonitorName, DateTime, Temperature, Humidity, Staleness)
VALUES (#ClientId, #MonitorName, #DateTime, #Temperature, #Humidity, #Staleness);
GO
Where proc GetClientId was
USE Testing
GO
CREATE PROCEDURE GetClientId
#ClientName nvarchar(50),
#ClientId bigint OUTPUT
AS
Select #ClientId = ClientID FROM Testing.dbo.Client WHERE ClientName = #ClientName
GO
Please let me know if you believe this to be the best way of doing this, or if there is a better way of doing it.

if you want to use like this:
DECLARE #ClientId int;
EXECUTE #ClientId = Testing.dbo.GetClientID #ClientName;
you can use RETURN #ClientID in the procedure
CREATE PROC proc_GetClientID
#ClientNeme VARCHAR(max)
AS
BEGIN
DECLARE #ClientID BIGINT
SELECT #ClientID=1000
RETURN #ClientID
END
DECLARE #ClientID INT
EXEC #ClientID =dbo.proc_GetClientID 'test'
SELECT #ClientID

Related

Get result parameter of stored procedure in exec clause

I have a stored procedure that returns multiple parameters:
CREATE PROCEDURE [dbo].[TestSP]
#Test1 INT
, #Test2 UNIQUEIDENTIFIER
--some inserts and alters here
SELECT TOP 1
#Parameter1 AS Design
, #Parameter2
, #Parameter3
FROM Table
I want to use EXEC into another stored procedure and get ONLY #Parameter1 (Design)
So I want to get #Parameter1 after EXEC stored procedure, so I think about OUTPUT, but it doesn't work, is there a way to achieve this?
CREATE PROCEDURE [dbo].[SecondStoredProcedure]
#Sender1 INT
, #Sender2 UNIQUEIDENTIFIER
DECLARE #ReturnedParameter1 INT
EXEC [dbo].[TestSP] #Test1 = #Sender1, #Test2 = #Sender2 OUTPUT [Design]
INTO #ReturnedParameter1
SELECT #ReturnedParameter1
That procedure creates a resultset, and has no output parameters. You can capture a resultset with insert into ... exec, like this:
use tempdb
go
CREATE PROCEDURE [dbo].[addDesign]
#Test1 INT
,#Test2 UNIQUEIDENTIFIER
as
begin
--some inserts and alters here
SELECT
1 AS Design
, 2 as Foo
, 3 as Bar
end
go
declare #rv table(Design int, Foo int, Bar int)
declare #test2 uniqueidentifier = newid()
insert into #rv
exec addDesign 1, #test2
declare #design int = (select Design from #rv)
select #design
I suggest using an output parameter as explained in the official docs.
Here is how your code might look in this case:
use tempdb
go
create procedure [dbo].[addDesign]
(
#Test1 int
, #Test2 uniqueidentifier
, #Design int out
)
as
begin
set nocount on;
--some inserts and alters here
-- Set the return parameter
set #Design = #Parameter1;
-- Select the return results
SELECT TOP 1
#Parameter1
, #Parameter2
, #Parameter3
FROM dbo.MyTable;
-- Return status code, proc ran OK
return 0;
end
go
create procedure [dbo].[SecondStoredProcedure]
(
#Sender1 int
, #Sender2 uniqueidentifier
)
as
begin
set nocount on;
declare #ReturnedParameter1 int;
exec dbo.TestSP #Test1 = #Sender1, #Test2 = #Sender2, #Design = #ReturnedParameter1;
select #ReturnedParameter1;
-- Return status code, proc ran OK
return 0;
end
go
Note: This demonstrates the 3 ways information can be returned from a stored procedure, the result code (only 1), output parameters (0-N) and result sets (0-N).

How can I return tables with different number of parameters with procedure?

I'm going to create different temp tables depending on the #selection parameter I get, and then I want to return the table I created.
I actually wanted to do it with the function, but I got an error for variable parameter tables. The sql procedur I wrote is as follows:
ALTER PROCEDURE [dbo].[Report]
(#Id BIGINT = 55,
#selection INT)
AS
BEGIN
IF #selection=1
BEGIN
Declare #tep_table table (Id int
,Name varchar(250)
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table
Select * from User
END
IF #selection=1
BEGIN
Declare #tep_table2 table (Id int
,CreateTime datetime
,UpdateTime datetime
,UpdatedBy varchar(250)
,Deleted bit
)
Insert into #tep_table2
Select * from Client
END
IF #selection=1
BEGIN
RETURN #tep_table
END
ELSE
BEGIN
RETURN #tep_table2
END
END
I am getting this error:
Must declare the scalar variable "#tep_table"
Personally I would turn this into three procedures to avoid the performance problems faced with multiple execution paths.
Something like this.
ALTER Procedure [dbo].[Report]
(
#Id bigint = 55 --not sure what the point of this parameter is as it wasn't used anywhere in the sample code
, #selection int
) AS
set nocount on;
IF #selection = 1
exec GetUserData;
IF #selection = 2
exec GetClientData;
GO
create procedure GetUserData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from [User];
GO
create procedure GetClientData
AS
set nocount on;
Select * --would prefer to use column names here instead of *
from Client;
GO

How to use SQL Variables inside a query ( SQL Server )?

I have written the following SQL Stored Procedure, and it keeps giving me the error at
#pid = SELECT MAX(... The whole procedure is:
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
#pid = SELECT MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Can anyone please tell me what I'm doing wrong here?
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SELECT #pid = MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
This has an advantage over SET with SELECT in that you can select expressions in multiple variables in one statement:
SELECT #var1 = exp1, #var2 = expr2 ... etc
declare #total int
select #total = count(*) from news;
select * from news where newsid = #total+2
//**news** table name and **newsid** column name
You need to use SET.
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SET #pid = (SELECT MAX(party_id)+1 FROM PARTY);
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Alternatively, in your case you could make party_id an autoincremented value, so you wouldn't need to query the table.

Store values in Stored Procedure

I created a SP as "SP_SELECT"
CREATE PROCEDURE SP_SELECT #userid varchar(50)
AS
BEGIN
SELECT Dept_Id from Master where User_Id=#userid
END
GO
Now the task is I have to store the Result (i.e) Dept_Id in a variable named as "dept" in the same stored procedure itself. Help me with the query.
Do you mean this?
CREATE PROCEDURE SP_SELECT #userid varchar(50)
AS
BEGIN
DECLARE #deptid int;
SET #deptid = SELECT Dept_Id from Master where User_Id=#userid
END
RETURN #deptid
GO
You could also pass #deptid as an output parameter in sql.
But this var will only exist each time the stored proc is run on the calling function or code you will still need to store the value.
i.e.
Declare #masterdeptid int;
SET #masterdeptid = EXEC SP_Select '123';
I ain't test the sql but you get the idea
try this one
set #dept= (select Dept_Id from Master where User_Id=#userid)
and if you want return this value to front end , write below code
set #dept= (select Dept_Id from Master where User_Id=#userid)
select #dept
This could be helpful to you
CREATE PROCEDURE USP_SELECT #userid varchar(50), #Dept int output
AS
BEGIN
SELECT #Dept = Dept_Id from Master where User_Id=#userid
END
above code can be executed as
Declare #Dept int;
EXEC USP_Select '123',#Dept output
Print #Dept

sql stored procedure

create PROC insert_Items(#Store varchar(20),#ID varchar(20),#Name varchar(20),#IDate varchar(11))
As
Declare #UDates varchar(11),
Declare #Quantity int,
Declare #Defects int
Select #Quantity From inserted
Select #Defects From Inserted
set #UDates = getdate(),
#Remanders = #Defects - #Quantity
Insert Items(StoreName,ProductID,ProductName,Quantity,Defects,InsertedDate,UpdatedDate)
Values(#Store,#ID,#Name,#Quantity,#Defects,#IDate,#UDates)
The question is i want to get the value for Remainder in my table l
If your table already contains a Remainder field, then simply add it to the INSERT statement like so :
Insert Items(StoreName, ProductID, ProductName, Quantity, Defects, InsertedDate, UpdatedDate, Remainder)
Values(#Store, #ID, #Name, #Quantity, #Defects, #IDate, #UDates, #Remainder)
A better option might be to make the Remainder column in the table a computed column. That way you'll always have the value, even if the data wasn't added through your stored procedure.
general practice is to declare an OUTPUT parameter for the procedure. The caller will then get that value as the parameter.
for example
create proc outputdemo(#invalue int, #outvalue int output)
as
set #outvalue = #invalue * 2
go
declare #myvalue int
exec outputdemo 10, #myvalue output
select #myvalue