Stored procedure unsure syntax - sql

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

Related

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

Stored procedure to search Table based on multiple values from dropdown

I have three down with different values such as
Category One dropdown
Category Two dropdown
Year dropdown
I Have to search Product table based on dropdown values it should filter search based on any one of the dropdown or all of the dropdown selected values.
Let us say i have following fields in Product Table
ProductID
ProductName
ProductCatOne
ProductCatTwo
Description
Image
....
....
How is the most efficient way to write a store procedure so that i cant handle any of the three value selected. I want to avoid two many if statements in store procedure
ALTER PROCEDURE [dbo].[sp_SearchProduct]
#ProductID int,
#ProductCatOne int,
#ProductCatTwo int
AS
BEGIN
SET NOCOUNT ON;
If #ProductID > 0 THEN
END IF
END
STORED PROCEDURE FOR MS SQL SERVER
I am not sure how to create dynamic query inside SP fr this search
It is called Dynamic Search Conditions. I recommend you to read this excellent article by Erland Sommarskog. He explains several ways to do it and why OPTION(RECOMPILE) is needed if you don't use dynamic SQL as in the example below.
Few notes.
It is bad practice to name your stored procedures with the prefix sp_.
I prefer to pass NULL value instead of 0 to indicate that this parameter should be ignored. 0 value can be a valid value for search.
ALTER PROCEDURE [dbo].[SearchProduct]
#ProductID int,
#ProductCatOne int,
#ProductCatTwo int
AS
BEGIN
SET NOCOUNT ON;
SELECT
...
FROM Products
WHERE
(ID = #ProductID OR #ProductID IS NULL)
AND (ProductCatOne = #ProductCatOne OR #ProductCatOne IS NULL)
AND (ProductCatTwo = #ProductCatTwo OR #ProductCatTwo IS NULL)
OPTION(RECOMPILE);
END
This code assumes that columns ID, ProductCatOne, ProductCatTwo can't have NULLs.
ALTER PROCEDURE [dbo].[sp_SearchProduct]
#ProductID int,
#ProductCatOne int,
#ProductCatTwo int
AS
BEGIN
SET NOCOUNT ON;
IF #ProductID =''
SET #ProductID=NULL
IF #ProductCatOne =''
SET #ProductCatOne=NULL
IF #ProductCatTwo =''
SET #ProductCatTwo=NULL
SELECT *
FROM Product
WHERE ID = COALESCE (#ProductID,ID)
AND ProductCatOne =COALESCE (#ProductID,ProductCatOne )
AND ProductCatTwo=COALESCE (#ProductID,ProductCatTwo)
END
ALTER PROCEDURE [dbo].[SearchProduct]
#ProductID int,
#ProductName int,
#ProductCatOne int
AS
BEGIN
SET NOCOUNT ON;
SELECT
...
FROM Products
WHERE
(Case When #ProductID <> 'ALL' Then ProductID Else #ProductID End ) in(#ProductID) And
(Case When #ProductName <> 'ALL' Then ProductName Else #ProductName End ) in(#ProductName) And
(Case When #ProductCatOne <> 'ALL' Then ProductCatOne Else #ProductCatOne End ) in(#ProductCatOne)
END

Sql Stored Procedure to insert and update

I am new to Stored Procedures and SQL. Looking in to various articles, I found how to insert an record using stored procedure and it works.
CREATE PROCEDURE [dbo].[stprOrder]
#OrderDate date,
#OrderID nchar(50),
#ShipToID nchar(50),
#TotalAmt decimal(18,2),
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
Values(#OrderDate,#OrderID,#ShipToID,#TotalAmt)
END
I am not sure how to update an record using the same stprOrder stored procedure. Like the stored procedure should do inserting and updating depending on the OrderID.
Most likely you're looking for something like this
CREATE PROCEDURE [dbo].[stprOrder]
#OrderDate date,
#OrderID nchar(50),
#ShipToID nchar(50),
#TotalAmt decimal(18,2),
AS
BEGIN
SET NOCOUNT ON;
IF (SELECT TOP (1) 1 FROM ORDER WHERE OrderID = #OrderID) IS NULL
INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
Values(#OrderDate,#OrderID,#ShipToID,#TotalAmt)
ELSE
UPDATE ORDER SET OrderDate = #OrderDate, ShipToID = #ShipToID, TotalAmt = #TotalAmt
WHERE OrderID = #OrderID
END
First it checks if order with given ID already exists - if it doesn't - a new entry is created, otherwise existing record is updated
CREATE PROCEDURE [dbo].[stprOrder]
#OrderDate date,
#OrderID nchar(50),
#ShipToID nchar(50),
#TotalAmt decimal(18,2),
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT null FROM ORDER WHERE id = #orderID)
BEGIN
UPDATE ORDER SET ..... WHERE id = #orderID
END
ELSE
BEGIN
INSERT INTO ORDER(OrderDate,OrderID,ShipToID,TotalAmt)
VALUES(#OrderDate,#OrderID,#ShipToID,#TotalAmt)
END

Count query doesn't work in store procedure

I am trying to select no of rows returned by select statement, but it returns 0, otherwise if I run simple count query, then it returns no of records being found WHY doesn't SP work for me ???
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50)
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #No_Rows int
Select No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Return #No_Rows
END
GO
This return 0,
Exec GetUser_Pwd 1, 1234
This returns 1
select count(*) from HrEmployee where EmplID = 1 AND PassWord = 1234
You will need to declare an OUTPUT variable. Try this:
CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50),
#No_Rows int OUTPUT
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Select #No_Rows= count(*)
from HrEmployee
where EmplID = #EmplID AND PassWord = #EmplPwd
RETURN
END
GO
Now, use the following to call the procedure
-- Declare the variable to receive the output value of the procedure.
DECLARE #No_Rows int;
-- Execute the procedure and save the output value in the variable #No_Rows
EXECUTE GetUser_Pwd #EmpId = '1',#EmplPwd='1234',#No_Rows=#No_Rows OUTPUT;
-- Display the value returned by the procedure.
PRINT 'Number of rows matching the criteria is ' +
convert(varchar(10),#No_Rows);
GO
Instead of RETURN #No_Rows write SELECT #No_Rows.
RETURN statement is used for Functions .
For Stored Procedure, RETURN statement is used if you are using OUTPUT paramater.
Read here on how to retrieve result from stored procedure
Declare #No_Rows int
Select #No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Select #No_Rows
CREATE PROCEDURE GetUser_Pwd
#EmplID char,
#EmplPwd varchar(50)
As
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Declare #No_Rows int
Select #No_Rows= count(*) from HrEmployee where EmplID = #EmplID AND PassWord = #EmplPwd
Return #No_Rows
END
GO
/Calling Like .../
DECLARE #x INT
EXEC #x = GetUser_Pwd #EmplID=1,#EmplPwd=1
SELECT #x

Stored Procedure OutPut Parameters

i need to write a stored procedure which will return a string.logic is
when user try to insert a new record i need to check whether that record already exist.if exist need to return msg "Record exist" else return "Inserted"
following is what i have done for the moment and i'm stuck here.can some one help me to complete the procedure
CREATE PROCEDURE [dbo].[spInsetPurpose]
#Purpose VARCHAR(500),
#Type VARCHAR(6),
#Result VARCHAR(10)= NULL OUTPUT
AS
BEGIN
Declare #Position VARCHAR(20)
DECLARE #TempTable TABLE (Purpose VARCHAR(500))
INSERT INTO #TempTable
SELECT Purpose FROM tblPurpose WHERE Purpose=#Purpose
INSERT INTO tblPurpose(Purpose,[Type]) VALUES(#Purpose,#Type)
END
To check if the row already exists you can do
If Exists (Select Top 1 1 from tblPurpose where Purpose = #Purpose and [Type] = #Type)
Begin
Insert Into tblPurpose
(Purpose, [Type])
Select
#Purpose, #Type
SET #Result = 'Inserted'
End
Else
Begin
SET #Result = 'Record exists'
End