How to pass more than one DepartmentId in SP? - sql-server

How to pass more than one DepartmentId in SP?
Execute spGetEmployeesByGender #DepartmentId =1 , #Gender = 'Male';

please refer to
Passing a list/array to an SQL Server stored procedure

Thanks Guys finally I alter the table like this
Create Procedure spGetEmployeesByID
#DepartmentId int
as
Begin
Select Name from tblEmployee Where DepartmentId IN (1 , 3)
End
Execute spGetEmployeesByID #DepartmentId = 1

Related

Stored Procedure return null for OUTPUT parameter in SQL Server 2017

Could you guys please help me to find the error in the below code.
CREATE PROCEDURE dbo.SelectCustomer2
(#customerId INT OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
SELECT #customerId = SCOPE_IDENTITY();
SELECT *
FROM Sales.Customer
WHERE CustomerID = #customerId;
END
--Executing SelectCustomer
DECLARE #lastRowId int
EXEC dbo.SelectCustomer2 #customerId = #lastRowId OUTPUT;
SELECT #lastRowId AS RowId
What am I doing wrong here?
Thanks in advance.
SCOPE_IDENTITY
Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, if two statements are in the same stored procedure, function, or batch, they are in the same scope.
if in your scope dont have any insert the SCOPE_IDENTITY(); is null
SCOPE_IDENTITY

Stored Procedure of counting duplicate value with output variable in MSSQL

I want to create stored procedure of counting duplicate value
here is code with out stored procedure
select count(PID) from tblPerson
group by Gender
tblPerson is my table and PID my primary key.
and this is my code for stored procedure and I need output so I have used it.
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson group by #gender= Gender
end
and this throws me error
Msg 102, Level 15, State 1, Procedure spcheckunique, Line 547
Incorrect syntax near '='.
Help me to fix this..
I think you are almost there:
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson
where #gender = gender
group by Gender
end
Use WHERE Condition instead of Group BY
create proc spcheckunique
#gender varchar(max),
#count int output
as
begin
SELECT #count=COUNT(PID)
from tblPerson WHERE #gender= Gender
end
I think the issue is here:
group by #gender= Gender
Remove the piece #gender =, you only need GROUP BY Gender.

SQL Server- Insert results from dynamic query and variable into same row of a temporary table

How do you insert the results of a dynamic SQL server query and a variable into the same row of a temp table.
Here is the format of the temporary table (#temp)
create TABLE #temp (YEAR INT, ACC_AMOUNT Money, REJ_AMOUNT Money, OUT_AMOUNT Money,TOT_AMOUNT Money)
The Stored PROC is executed by
exec sp_executesql #pSQL
and will return values that should go into the columns ACC_AMOUNT, REJ_AMOUNT, OUT_AMOUNT.
14569849.11 696235.49 1353464.92 16619549.52
I want to insert a variable (#pACCU_YEAR) for the Year and the results of the SP and insert the dyanmic query in the same Row. This is wrong, but this will give you an idea of what I mean.
insert into #temp (YEAR)
values (#pACCU_YEAR)
insert into #temp (ACC_AMOUNT , REJ_AMOUNT, OUT_AMOUNT,TOT_AMOUNT)
exec sp_executesql #pSQL
This will result in
YEAR ACC_AMOUNT REJ_AMOUNT OUT_AMOUNT TOT_AMOUNT
2014 NULL NULL NULL NULL
NULL 14569849.11 696235.49 1353464.92 16619549.52
I would like:
YEAR ACC_AMOUNT REJ_AMOUNT OUT_AMOUNT TOT_AMOUNT
2014 14569849.11 696235.49 1353464.92 16619549.52
Select #Year [Year]
,Acc_Amount
,other fields....
FROM #Temp
In response to the question asked in your comment.
Use this after the #pSql is run. Leave the column Year out of the declaration.
Alternatively, after it runs just:
update #temp
SET [Year]=#Year
What's the code inside #pSQL? Why don't do the INSERT in your dynamic query itself like
declare #pSQL varchar(max);
set #pSQL = 'some sql command;
some_other_sql_command;
.......
insert into #temp (ACC_AMOUNT , REJ_AMOUNT, OUT_AMOUNT,TOT_AMOUNT)
select blah,blah1,blah2,blah3
from blah_table;';
exec sp_executesql #pSQL;
can you please show me an example of how to select a column that is a
variable not within the table?
use same SELECT statement like
select #var1 as some_name, #var2 as some_other_name
as some_name is optional. That's to give a meaningful name to the selected field.

SQL Server: how to create a stored procedure

I'm learning sql from a book and I'm trying to write a stored procedure but I don't believe that I'm doing it correctly. Is the following way not valid in Microsoft SQL? If not, when is it valid, if ever?
create procedure dept_count(in dept_name varchar(20), out d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
I get the following error
Msg 156, Level 15, State 1, Procedure wine_change, Line 1
Incorrect syntax near the keyword 'in'.
T-SQL
/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/
CREATE PROCEDURE GetstudentnameInOutputVariable
(
#studentid INT, --Input parameter , Studentid of the student
#studentname VARCHAR (200) OUT, -- Output parameter to collect the student name
#StudentEmail VARCHAR (200)OUT -- Output Parameter to collect the student email
)
AS
BEGIN
SELECT #studentname= Firstname+' '+Lastname,
#StudentEmail=email FROM tbl_Students WHERE studentid=#studentid
END
In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:
CREATE PROCEDURE dept_count
(
-- Add input and output parameters for the stored procedure here
#dept_name varchar(20), --Input parameter
#d_count int OUTPUT -- Output parameter declared with the help of OUTPUT/OUT keyword
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Statements for procedure here
SELECT #d_count = count(*)
from instructor
where instructor.dept_name=#dept_name
END
GO
and to execute above procedure we can write as:
Declare #dept_name varchar(20), -- Declaring the variable to collect the dept_name
#d_count int -- Declaring the variable to collect the d_count
SET #dept_name = 'Test'
Execute dept_count #dept_name,#d_count output
SELECT #d_count -- "Select" Statement is used to show the output
I think it can help you:
CREATE PROCEDURE DEPT_COUNT
(
#DEPT_NAME VARCHAR(20), -- Input parameter
#D_COUNT INT OUTPUT -- Output parameter
-- Remember parameters begin with "#"
)
AS -- You miss this word in your example
BEGIN
SELECT COUNT(*)
INTO #D_COUNT -- Into a Temp Table (prefix "#")
FROM INSTRUCTOR
WHERE INSTRUCTOR.DEPT_NAME = DEPT_COUNT.DEPT_NAME
END
Then, you can call the SP like this way, for example:
DECLARE #COUNTER INT
EXEC DEPT_COUNT 'DeptName', #COUNTER OUTPUT
SELECT #COUNTER
Try this:
create procedure dept_count(#dept_name varchar(20),#d_count int)
begin
set #d_count=(select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name)
Select #d_count as count
end
Or
create procedure dept_count(#dept_name varchar(20))
begin
select count(*)
from instructor
where instructor.dept_name=dept_count.dept_name
end
CREATE PROCEDURE [dbo].[USP_StudentInformation]
#S_Name VARCHAR(50)
,#S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Date VARCHAR(50)
SET #Date = GETDATE()
IF EXISTS (
SELECT *
FROM TB_StdFunction
WHERE S_Name = #S_Name
AND S_Address = #S_Address
)
BEGIN
UPDATE TB_StdFunction
SET S_Name = #S_Name
,S_Address = #S_Address
,ModifiedDate = #Date
WHERE S_Name = #S_Name
AND S_Address = #S_Address
SELECT *
FROM TB_StdFunction
END
ELSE
BEGIN
INSERT INTO TB_StdFunction (
S_Name
,S_Address
,CreatedDate
)
VALUES (
#S_Name
,#S_Address
,#date
)
SELECT *
FROM TB_StdFunction
END
END
Table Name : TB_StdFunction
S_No INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)
Create this way.
Create procedure dept_count(dept_name varchar(20),d_count integer)
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
try this:
create procedure dept_count( #dept_name varchar(20), #d_count INTEGER out)
AS
begin
select count(*) into d_count
from instructor
where instructor.dept_name=dept_count.dept_name
end
To Create SQL server Store procedure in SQL server management studio
Expand your database
Expand programmatically
Right-click on Stored-procedure and Select "new Stored Procedure"
Now, Write your Store procedure, for example, it can be something like below
USE DatabaseName;
GO
CREATE PROCEDURE ProcedureName
#LastName nvarchar(50),
#FirstName nvarchar(50)
AS
SET NOCOUNT ON;
//Your SQL query here, like
Select FirstName, LastName, Department
FROM HumanResources.vEmployeeDepartmentHistory
WHERE FirstName = #FirstName AND LastName = #LastName
GO
Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (#LastName and #FirstName) and type = parameter type example nvarchar(50) etc.
Source: Stored procedure in sql server (With Example)
To Execute the above stored procedure you can use sample query as below
EXECUTE ProcedureName #FirstName = N'Pilar', #LastName = N'Ackerman';

Can you call a SQL Stored Procedure that returns a record set and have those values loaded into variables?

Please consider the following SQL Server table and stored procedure.
create table customers(cusnum int, cusname varchar(50))
insert into customers(cusnum, cusname) values(1, 'Ken')
insert into customers(cusnum, cusname) values (2, 'Violet') --The Wife
create procedure getcus
#cusnum int
as
Begin
select cusname
from customers (nolock)
where cusnum = #cusnum
End
You know how you can write T-SQL code like this:
declare #cusname varchar(50)
select #cusname = cusname
from customers
where cusnum = 1
Can I do this with my stored procedure?
for example the code would look like this:
declare #cusnum int
declare #cusname varchar(50)
set #cusnum = 1
exec #cusname = cusname pbogetcus #cusnum
Thanks in advance.
No, you can't return values like that.
You need to use OutputParameters: MSDN.
EDIT:
This might be a better link:
SQL Team
Check out the section about midway down: Using OUTPUT variables

Resources