Stored Procedure of counting duplicate value with output variable in MSSQL - sql-server

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.

Related

Run a stored procedure and export its values for an entire month

As it stands my colleague will be running the below query 30 times.
EXEC dbo.usp.Nameofstoredprocedure '01-nov-2016'
It exports 3 rows with columns ID, Name, type
Is there anyway to have it export as:
Date, ID, name, type
01-nov-2016,10,john smith,man
01-nov-2016,11,jane smith,woman
02-nov-2016,10,john smith, man
02-nov-2016,11,jane smith,woman
etc..
The stored procedure in question is not something I can copy and paste in due to policy.
Thinking it over, I can see a loop might work, possibly inserting the row into a table but I can't figure out how to do this, any assistance would be great.
Work so far:
declare #date date
set #date = '2016-11-01'
declare #inte int
while #inte >= 30
select * into #temp EXEC dbo.usp_GetMaxUsers #date
set #date = DATEADD(dd,1,#date)
set #inte = #inte + 1
Right now it's giving me the following error:
Msg 263, Level 16, State 1, Line 4
Must specify table to select from.
Msg 1038, Level 15, State 5, Line 4
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
Thanks.
You could try this:
CREATE TABLE <Table Name>
(
Date DateTime,
ID INT,
Name NVARCHAR(40),
Type NVARCHAR(6)
)
INSERT INTO <Table Name>
Exec <SP NAME> 'Params'
You need to run the create table only once of course then put the rest into an agent job to run whenever you need it to.
The real problem is the stored procedure should be redone to meet the requirements. Database objects often need refactoring too.
I would add an enddate optional parameter (with a default value of null, so it won't break existing uses of the proc). Then if only the first date was sent in, it would set the end date to the correct value to get only records from that date. Otherwise it would use both dates in the internal query(ies) to get the information over a date range.
The answer that worked.
declare #date2 date
set #date2 = '2016-11-01'
declare #inte int=0
while #inte <= 29
begin
create table #temp
(
ID int,
Name varchar(100),
Type varchar(50)
)
insert into #temp
exec [dbo].[usp_proceduregoeshere] #date2
insert into #Results
select #date2, *
from #Agents
drop table #temp
set #date2 = dateadd(day, 1, #date2)
set #inte = #inte+1
end
select *
from #Results

How to pass more than one DepartmentId in SP?

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

insert a field value into a table from c# Form application

I want to Insert a DateTime variable into a table by " Insert into " , I mean by using from coding not wizard.
fro example I have a table which has a some field and one of them is Time_1 and I've write a procedure which its duty is filling Information to my table and in my procedure I've used from :
Insert into my_table
values
('#name','#last_Name',#ID,#Time)
but SQL show error when I enter 12:45:00 for #Time
so please tell me how to enter times into my filed .
Thanks in advance
create procedure Insert_List
#code int, #name nvarchar(20),#lastname nvarchar(40),#time1 datetime,#time2 datetime,
#time3 datetime,#price1 int,#price2 int, #B1 int , #V1 int , #M1 int
as
begin
insert into Employee
values
(#code,#name,#lastname,#time1,#time2,#time3,#price1,#price2,#B1,#V1,#M1)
end
//and I try to execute my procedure by these information
execute Insert_List 1,'Keyvan','Fardi',10:00:00,18:15:00,19:10:00,10,10,10,10
select * from employee
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ':'.
Insert into my_table values ('#name','#last_Name',#ID,#Time)
Since you are using a parameterized SQL statement, do not enclose the parameters in quotes. Instead:
INSERT INTO my_table VALUES (#name, #last_Name, #ID, #Time);
If you are still getting an error, post the error message and all proc code.

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';

result set based on success or failure

I'm having a stored procedure which returns two result sets based on the success or failure.
SP success result set: name, id ,error,desc
SP failure result sret: error,desc
I'm using the following query to get the result of the stored procedure. It returns 0 for success and -1 for failure.
declare #ret int
DECLARE #tmp TABLE (
name char(70),
id int,
error char(2),
desc varchar(30)
)
insert into #tmp
EXEC #ret = sptest '100','King'
select #ret
select * from #tmp
If the SP is success the four field gets inserted into the temp table since the column matches.
But in case of failure the sp result set has only error and desc which does not matchs with no of columns in the temp table...
.I can't change the Sp, so I need to do some thing (not sure) in temp table to handle both failure and success.
You can't return 2 different recordsets and load the same temp table.
Neither can try and fill 2 different tables.
There are 2 options.
Modify your stored proc
All 4 columns are returned in all conditions
1st pair (name, ID) columns are NULL on error
2nd pair (error, desc) are NULL on success
If you are using SQL Server 2005 then use the TRY/CATCH to separate your success and fail code paths. The code below relies on using the new error handling to pass back the error result set via exception/RAISERROR.
Example:
CREATE PROC sptest
AS
DECLARE #errmsg varchar(2000)
BEGIN TRY
do stuff
SELECT col1, col2, col3, col4 FROM table etc
--do more stuff
END TRY
BEGIN CATCH
SELECT #errmsg = ERROR_MESSAGE()
RAISERROR ('Oops! %s', 16, 1, #errmsg)
END CATCH
GO
DECLARE #tmp TABLE ( name CHAR(70), id INT, error char(2), desc varchar(30)
BEGIN TRY
insert into #tmp
EXEC sptest '100','King'
select * from #tmp
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH
My fault!!
Was too quick in the answer.
You need only to relv on the return value, so building up the logic against it is much better.
If you still want to use the temp table, then calling the sptest twice could be a way to deal with it (not optimal though), one time to get the return value and based on it then have 2 different temp tables you are filling up (one would be with the 4 fields, the other only with 2 fields).
declare #ret int
DECLARE #tmp TABLE (name CHAR(70), id INT, error char(2), desc varchar(30))
DECLARE #tmperror TABLE (error char(2), desc varchar(30))
EXEC #ret = sptest '100','King'
IF #ret != 0
BEGIN
INSERT INTO #tmperror
EXEC sptest '100','King';
SELECT * FROM #tmperror;
END
ELSE
BEGIN
INSERT INTO #tmp
EXEC sptest '100','King';
SELECT * FROM #tmp;
END
Keep in mind that this solution is not optimal.
Try modifying your table definition so that the first two columns are nullable:
DECLARE #tmp TABLE (
name char(70) null,
id int null,
error char(2),
desc varchar(30)
)
Hope this helps,
Bill
You cannot do this with just one call. You will have to call it once, either getting the return status and then branching depending on the status to the INSERT..EXEC command that will work for the number of columns that will be returned or Call it once, assuming success, with TRY..CATCH, and then in the Catch call it again assuming that it will fail (which is how it got to the CATCH).
Even better, would be to either re-write the stored procedure so that it returns a consistent column set or to write you own stored procedure, table-valued function or query, by extracting the code from this stored procedure and adapting it to your use. This is the proper answer in SQL.

Resources