Store values in Stored Procedure - sql

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

Related

SQL Server : use bigint variable in stored procedure

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

Stored procedure unsure syntax

I am trying to create a stored procedure that will determine if my customerid exists if it exists then my other parameter foundcustomer will be assigned to found otherwise not found. I am unsure how to assign found please help
here is what i tried
CREATE PROCEDURE procedure4
-- Add the parameters for the stored procedure here
#FoundCustomer varchar(10) = null,
#Customerid varchar (5) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if Not(#Customerid is null)
SELECT customerid
from customers
where customerid = #Customerid
END
GO
Gordon is right, it sounds like you may want a function but if it has to be a stored procedure you can follow this example.
CREATE PROCEDURE procedure4
#Customerid varchar(5) = null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #FoundCustomer varchar(10) = ''
IF #FoundCustomer is not null
BEGIN
IF (SELECT COUNT(1) FROM customers WHERE customerid = #customerid) > 0
SET #FoundCustomer = 'Found'
ELSE
SET #FoundCustomer = 'Not Found'
END
SELECT #FoundCustomer
END

Save execute procedure results into a var in SQL Server 2008

I have a procedure that executes another procedure and I need to save the results into a variable.
How can I do that?
ALTER PROCEDURE sp_GetDetailsByUserId
#userId int
AS
BEGIN
SELECT
usr.FirstName, usr.LastName, usr.UserName, usr.Email
FROM
[User] usr
WHERE
usr.UserID = #userId
EXEC sp_GenerateRandomPass #userId // this result need to be inside a var
END
I am a beginner and need help.
Thank you.
you can declare a Table or you can use a Temp Table:
ALTER PROCEDURE sp_GetDetailsByUserId
#userId int
AS
BEGIN
SELECT usr.FirstName, usr.LastName, usr.UserName, usr.Email
FROM [User] usr
WHERE usr.UserID = #userId
declare #tbl table (the columns should be compatible with the result columns)
insert into #tbl
exec sp_GenerateRandomPass #userId // this result need to be inside a var
END
with temptable you can do:
ALTER PROCEDURE sp_GetDetailsByUserId
#userId int
AS
BEGIN
SELECT usr.FirstName, usr.LastName, usr.UserName, usr.Email
FROM [User] usr
WHERE usr.UserID = #userId
create table #tempTable(the columns should be compatible with the result columns)
insert into #tempTable
exec sp_GenerateRandomPass #userId // this result need to be inside a var
END
Can you change the procedure? Having output parameters would probably be best, assuming the select always returns just one row.
exec sp_GenerateRandomPass #userId, #password output
output parameters work this way:
ALTER PROCEDURE sp_GenerateRandomPass
#userId int,
#password varchar (100) output
AS
BEGIN
-- Magic happens
set #password = 'xxxx'
END
Other option is to change GenerateRandomPass to be a scalar function, you can assign value from it to a variable directly in your procedure
Also, please do not prefix your procedures with "sp_", it's intended for built in procedures.
You need to modify sp_GenerateRandomPass , Store result of query within this stored procedure to temptable. Find more about temptable.
Temp table will be accessible among stored procedures. So you can use that in sp_GetDetailsByUserId

SQL: How to make table name in stored procedure dynamic

I am pretty new to SQL Server and hope someone here can help me with this (I'm using QL Server 2008).
The following is a small procedure that works as intended.
Now I would like to use the same procedure to update multiple tables as all these tables have exactly the same column names and column formatting, the only difference is the 2nd part of the table name for which I added XXX below.
Can someone tell me how this could be made dynamic and also provide me some explanations on this ?
I cannot provide much more here as I wasn't sure about how to approach this - other than probably declaring #sql nvarchar(max) and wrapping the whole query in SET #sql = N'...' before executing it.
My stored procedure:
CREATE PROCEDURE [dbo].[Cal_UpdateTeam]
#team nvarchar(100),
#teamID int,
#notes nvarchar(1000),
#log nvarchar(100),
#admin varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
IF NOT EXISTS
(
SELECT *
FROM Cal_XXX
WHERE teamID = #teamID
)
INSERT INTO Cal_XXX
(
team,
teamID,
notes,
log,
admin
)
SELECT #team,
#teamID,
#notes,
#log,
#admin
ELSE
UPDATE Cal_XXX
SET team = #team,
teamID = #teamID,
notes = #notes,
log = #log,
admin = #admin
WHERE teamID = #teamID
END
END
Many thanks for any tips and advise on this, Mike.
you should wrap your sql query in an nvarchar and then execute that query as in the below example :
declare #sql nvarchar(max)
declare #TableName nvarchar(max)
set #TableName = 'mytable'
set #sql = 'Select * from ' + #TableName
Exec sp_executesql #sql
in SP you can use Temporary Tables fro example:
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/*************************************
** Temporary table **
*************************************/
CREATE TABLE #SOURCE (
ID INT
, ID_PARENT INT
, NAME VARCHAR(200)
, SORT INT
..
..
)
IF #REQUEST_ID = 'YES' BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_A
END
ELSE BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_B
END
SELECT * FROM #SOURCE
.....
END
GO
in SP you can encapsulate other SPs with different table names like parameter:
CREATE PROCEDURE SELECT_FROM_TABLE_A
AS
BEGIN
SELECT * FROM SOURCE_A
END
GO
CREATE PROCEDURE SELECT_FROM_TABLE_B
AS
BEGIN
SELECT * FROM SOURCE_B
END
GO
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/**********************************************
** Subrequest select **
**********************************************/
IF #REQUEST_ID = 'YES' BEGIN
-- Request SP fro Source A
EXEC SELECT_FROM_TABLE_A
END
ELSE
BEGIN
-- Request SP fro Source B
EXEC SELECT_FROM_TABLE_B
END
END
GO

How to return the output of stored procedure into a variable in sql server

I want to execute a stored procedure in SQL Server and assign the output to a variable (it returns a single value) ?
That depends on the nature of the information you want to return.
If it is a single integer value, you can use the return statement
create proc myproc
as
begin
return 1
end
go
declare #i int
exec #i = myproc
If you have a non integer value, or a number of scalar values, you can use output parameters
create proc myproc
#a int output,
#b varchar(50) output
as
begin
select #a = 1, #b='hello'
end
go
declare #i int, #j varchar(50)
exec myproc #i output, #j output
If you want to return a dataset, you can use insert exec
create proc myproc
as
begin
select name from sysobjects
end
go
declare #t table (name varchar(100))
insert #t (name)
exec myproc
You can even return a cursor but that's just horrid so I shan't give an example :)
You can use the return statement inside a stored procedure to return an integer status code (and only of integer type). By convention a return value of zero is used for success.
If no return is explicitly set, then the stored procedure returns zero.
CREATE PROCEDURE GetImmediateManager
#employeeID INT,
#managerID INT OUTPUT
AS
BEGIN
SELECT #managerID = ManagerID
FROM HumanResources.Employee
WHERE EmployeeID = #employeeID
if ##rowcount = 0 -- manager not found?
return 1;
END
And you call it this way:
DECLARE #return_status int;
DECLARE #managerID int;
EXEC #return_status = GetImmediateManager 2, #managerID output;
if #return_status = 1
print N'Immediate manager not found!';
else
print N'ManagerID is ' + #managerID;
go
You should use the return value for status codes only. To return data, you should use output parameters.
If you want to return a dataset, then use an output parameter of type cursor.
more on RETURN statement
Use this code, Working properly
CREATE PROCEDURE [dbo].[sp_delete_item]
#ItemId int = 0
#status bit OUT
AS
Begin
DECLARE #cnt int;
DECLARE #status int =0;
SET NOCOUNT OFF
SELECT #cnt =COUNT(Id) from ItemTransaction where ItemId = #ItemId
if(#cnt = 1)
Begin
return #status;
End
else
Begin
SET #status =1;
return #status;
End
END
Execute SP
DECLARE #statuss bit;
EXECUTE [dbo].[sp_delete_item] 6, #statuss output;
PRINT #statuss;
With the Return statement from the proc, I needed to assign the temp variable and pass it to another stored procedure. The value was getting assigned fine but when passing it as a parameter, it lost the value. I had to create a temp table and set the variable from the table (SQL 2008)
From this:
declare #anID int
exec #anID = dbo.StoredProc_Fetch #ID, #anotherID, #finalID
exec dbo.ADifferentStoredProc #anID (no value here)
To this:
declare #t table(id int)
declare #anID int
insert into #t exec dbo.StoredProc_Fetch #ID, #anotherID, #finalID
set #anID= (select Top 1 * from #t)