Dynamic Where Condition Based on Parameter - sql

I have a parameter based on which I need to include or exclude one condition in a where clause.
If the CustomerType parameter is blank, then I need to include a condition CustomerType is null, otherwise I need to exclude that CustomerType is null condition.
The SQL query is:
IF(#CustomerType = Blank)
BEGIN
Select * From Customer
Where
(CustomerType IN(#Type) Or CustomerType is null)
END
Else
Begin
Select * From Customer
Where
CustomerType IN(#Type)
End
Is there a better way to include or exclude this condition without using an IF ELSE condition like above?

Try
Select * From Customer
Where
(CustomerType is null AND #customertype ='')
OR
CustomerType IN (#Type)
You need change your "IN" part , however.
Edit:
Select * From Customer
Where (#customertype ='') OR CustomerType IN (...)
To handle all those input in one stored procedure:
CREATE PROCEDURE FIND_CUSTOMER_BY_TYPE #TYPE VARCHAR(50)
AS
BEGIN
-- a lazy check on your parameters
IF #TYPE LIKE '%[^0-9, ]%' BEGIN
RAISERROR('Invalid parameter',16,1);
return;
End;
SET NOCOUNT ON;
DECLARE #SQL VARCHAR(500);
SET #SQL='SELECT * FROM CUSTOMERS';
IF #TYPE>''
SET #SQL = #SQL + ' WHERE CUSTOMER_TYPE IN ('+#TYPE+')';
EXEC(#SQL);
SET NOCOUNT OFF;
END;
Your program can all this procedure with the parameter.

Related

Parameter in LIKE statement only returning exact values

I have a parameterized query shown below that is supposed to return info about items that have a name like the parameter. However, it only works for exact matches
BEGIN
SET NOCOUNT ON
DECLARE #name varchar(50)
SET #name = 'bananas'
SELECT category, sum(netweight) AS NetWeight from PieChart group by
category, name HAVING name LIKE #name
END
Since 'bananas' is in the database, it returns that info. If it put 'banan', it returns nothing.
Thanks for your help!
You can also put the wildcards in the WHERE clause:
BEGIN
SET NOCOUNT ON;
DECLARE #name VARCHAR(50) = 'bananas';
SELECT category ,
SUM(netweight) AS NetWeight
FROM PieChart
WHERE [name] LIKE '%' + #name + '%'
GROUP BY category ,
[name]
END
You need wildcards. In addition, you should use where, not having. So:
BEGIN
SET NOCOUNT ON
DECLARE #name varchar(50);
SET #name = 'banan%';
SELECT category, sum(netweight) AS NetWeight
FROM PieChart
WHERE name LIKE #name
GROUP BY category, name;
END;

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

Put Where Clause in a parameter

I would like to use a where clause in a parameter. I already tried the following code but it doesnt work. the last line us red underlined, i reckon that i have to bind the parameter to the select command somehow. Would be great if anyone could help me with it.
Begin
declare #name varchar(MAX)
declare #x int
Set #x = 1
If #x = 1
BEGIN
SET #name = 'WHERE Username = Frank'
END
ELSE
BEGIN
SET #name = ''
END
END
now use it in:
SELECT * FROM dbo.person #name
Here is a typical way to have optional parameters in a query:
declare #UserName varchar(255) = 'Frank'
select *
from person p
where (#UserName is null or UserName = #UserName)
If you set the variable to NULL then all users are chosen. If you set it to a value, then only that user is chosen.
Looks like you want an optional Stored Procedure parameter to either pull rows with the parameter value or pull all rows:
CREATE PROCEDURE foo
#name AS VARCHAR(MAX) = NULL
AS
BEGIN
SELECT * FROM dbo.person WHERE Username = #name OR #name IS NULL
END
GO

How to select Table and Column Names from passed parameters in SQL Server?

I have two very similar tables in our database, and I need to write a stored procedure for my Visual Studio 2010 Web Application to read the data from one of these tables given a table number.
Currently, we only have two tables to select from, but I can see this growing to more as this project grows.
This is sort of what I am trying to do, but this code is not correct:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
select #col1 as 'Request', WorkOrder, PartNumber, Qty, EmployeeID
from #table
END
Basically, the ColumnName and TableName depend on the #tableID parameter that will be passed in.
How would I go about doing that?
Note: My searches are not turning up anything related, but I am a C# developer and not a database developer. I imagine this has been asked before, it is just I am not using the right keywords.
Although I think Mark is quite correct given the small number of tables and simplicity of your queries, here is a dynamic sql example that passes both the table and column names:
CREATE PROCEDURE spGetData
(
#TableName nvarchar(128),
#ColumnName nvarchar(128)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(4000)
SET #SQL = 'SELECT ' + #ColumnName + ', as Request, WorkOrder, PartNumber, Qty, EmployeeID FROM ' + #TableName
EXEC sp_executesql #SQL
END
You can call it as follows:
exec spGetData 'SMRequest', 'SMRequestID'
exec spGetData 'WHRequest', 'WHRequestID'
One option would be to use a conditional based upon the ID and put the code for a specific table in each section for the table.
I prefer this method to get away from the dynamic sql and allow the database server to get a fighting chance to optimize the thing for speed reasons by precompiling.
NOTE: database servers are pretty bad at string manipulation (create dynamic sql) in general.
EDIT1: EXAMPLE
FOR INSTANCE: THIS SQL
declare #mytest varchar(5)
set #mytest = 'PROCS'
IF #mytest = 'PROCS'
BEGIN /* STORED PROCS */
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'P'
END
ELSE
IF #mytest = 'DEFAULT'
BEGIN
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'D'
END
gives you the store procedure names or the default constraints depending on what you pass to the parameter.
EDIT2: Based on OP code:
CREATE PROCEDURE [dbo].[spGetData]
(#tableID int )
AS
BEGIN
SET NOCOUNT ON;
IF #tableID = 1
BEGIN
SELECT SMSRequestId AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM SMRequest
END
IF #tableID = 2
BEGIN
SELECT WHRequestID AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM WHRequest
END
END
Do it with dynamic SQL:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50), #cmd nvarchar(400)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
#cmd = "select " + #col1 + " as 'Request', WorkOrder, PartNumber, Qty, EmployeeID from " + #table
EXEC(#cmd)
END

Make a normal query from a stored procedure

Using VB6 and SQL Server 2000
I want to convert a stored procedure to normal query
Stored procedure:
Alter PROC [dbo].[proc_New]
#CCODE VARCHAR(100),
#EmpCode VARCHAR(100)
AS
BEGIN
DECLARE #ID VARCHAR (5)
DECLARE #Des VARCHAR(10)
DECLARE #SQL VARCHAR(1000)
DECLARE #Flag INT
SELECT #Flag=0
SELECT #SQL = 'SELECT PERSONID FROM T_PERSON WHERE '
IF #CCODE<>'All'
BEGIN
IF #Flag=1
BEGIN
SELECT #SQL = #SQL+' AND (CCODE IN ('''+#CCODE+'''))'
END
ELSE
BEGIN
SELECT #SQL = #SQL+' (CCODE IN ('''+#CCODE+'''))'
SELECT #Flag=1
END
END
IF #EMPCODE<>'All'
BEGIN
IF #Flag=1
BEGIN
SELECT #SQL = #SQL+' AND (EMPCODE IN ('''+#EMPCODE+'''))'
END
ELSE
BEGIN
SELECT #SQL = #SQL+' (EMPCODE IN ('''+#EMPCODE+'''))'
SELECT #Flag=1
END
END
IF #SQL = 'SELECT EmpCode FROM EMPMST WHERE ' SELECT #SQL = 'SELECT EmpCode FROM EMPMST'
INSERT INTO table EXEC(#SQL)
GO
Procedure Explanation...
I am passing 2 parameter values like emp_code or All and company_code or All.
In the 1st parameter (Emp_Code): if the value is "All" means then query return the all the emp_code or If the values is "001" then query return the "001" emp_code only
In the 2nd Parameter (Company_Code): if the value is "All" means then query return the all the emp_code for all the company (ex: IBM, SoftTech, etc) or If the value is "IBM" means then query return all the emp_code for that company (IBM)
Above stored procedure is working fine, but I want to convert into normal query.
Can anybody help me
Need query help
Below is the simpler query, please try with this:
SELECT PERSONID FROM T_PERSON WHERE
CCODE = (
CASE WHEN #CCODE = 'ALL' THEN CCODE
ELSE #CCODE END
)
AND
EMPCODE = (
CASE WHEN #EMPCODE = 'ALL' THEN EMPCODE
ELSE #EMPCODE
END
)
You can't directly do this in SQL outside of a stored procedure, your stored procedure has several if/else statements, no structure exists in sql queries to do this, if you want to achieve this you will need to build in sripting logic from the language accessing it with (i.e. c#/php/coldfusion/etc) and then perform the individual queries.
What Language are you calling the stored procedure from, or is this directly from the SQL server?
Edit: I have not used VB6 in a while so I don't remember how to write this in VB but you would basically be copying the logic from the stored procedure to build the query and then sending the query directly from VB not letting the stored procedure do it.
e.g.
Dim sql As String
If CCODE <> 'All'
sql = 'SELECT PERSONID FROM T_PERSON WHERE AND (CCODE IN (' & CCODE & '));'
{send the query to sql server}
End If