Querying different table based on a parameter - sql

I have a stored procedure that I would like to query either the production or the "work in progress" table, based on the parameter I am passing in. I could write two separate stored procedures, but I thought this was worth a try.
something along the lines of:
create procedure getUserDetails
#userID int,
#prod varchar(5)
as
begin
select * from
if (#prod = 'true')
Begin
userprod_table
else
userwip_table
end
where something = 'something'
END
Is this at all possible? I wouldn't want to write 2 SP that are almost identical :-/

Why not use a simple if(#prod = 'true') statement like below:
if (#prod = 'true')
begin
select * from userprod_table where something = 'something'
end else
begin
select * from userwip_table where something = 'something'
end

You could use a CTE so that your main query isn't repeated
with usertable as
(
select * from userprod_table where 1 = #flag
union
select * from userwip_table where 0 = #flag
)
select ... from usertable ...

Related

Use NULL as a valid value in a stored procedure

I have a stored procedure with one parameter, #ID, which is an integer that might be zero. When it is zero, I want to use it as if it is null. So here is how I have written my query:
If #ID = 0
SELECT * FROM MyTable WHERE ID IS NULL
ELSE
SELECT * FROM MyTable WHERE ID = #ID;
This is quite inelegant. Surely there is a way to write the WHERE clause in such a way that makes duplicating the SELECT statement unnecessary.
You can phrase this more simply using:
SELECT *
FROM MyTable
WHERE COALESCE(ID, 0) = #id;
Next, you probably do not want to do this. It will prevent SQL Server from using an index. Similarly, OR is likely to prevent optimization as well.
Probably your best bet is your current code, or UNION ALL:
SELECT *
FROM MyTable
WHERE ID IS NULL AND #id = 0
UNION ALL
SELECT *
FROM MyTable
WHERE ID = #ID; -- not sure if `#id <> 0` is needed here
With this or your approach, you probably need OPTION (RECOMPILE) to ensure that an index is always used.
Just combine them using AND/OR logic:
SELECT *
FROM MyTable
WHERE (#Id != 0 AND ID = #ID)
OR (#Id = 0 AND ID IS NULL);

How to use case statement inside an SQL select Query

I need to get the output of a selected query depending on certain conditions
Means if(id=uid)
then I need the below query
select * from table1 where id=5;
else
I need the below one
select * from table1 where id=10
I know i can use if condition for this. But my query is very long one so when I use if else then it would look like
if(#id=#uid)
begin
select * from table1 where id=5;// query 1
end
else
select * from table1 where id=10;//query 2
but here I need to replace the entire query once again for a single check. I hope I can do something like this:
declare #id int=4;
declare #uid=10;
select * from table1 where
case
when #id=#uid
then
id=5
else
id=10;
end
Updation
I need one more condition too
in this case id=5 and uid=10
then if(id=uid)
then
select * from table1 where id=5
and
if(id!=uid)
then
select * from table1
something like this
You can use the case expression to return the value id should be equal to:
SELECT *
FROM table1
WHERE id = CASE WHEN #id = #uid THEN 5 ELSE 10 END;
EDIT:
The updated requirement in the question is to return all rows when #id != #uid. This can be done by comparing id to id:
SELECT *
FROM table1
WHERE id = CASE WHEN #id = #uid THEN 5 ELSE id END;
Alternatively, with this updated requirement, a simple or expression might be simpler to use:
SELECT *
FROM table1
WHERE #id = #uid OR id = 5;
SELECT * FROM table1
WHERE (id=5 AND #id=#uid) OR (id=10 AND #id<>#uid)
SELECT
*
FROM
table1
WHERE
(
#id = #uid
AND
id =5
)
OR
(
not #id = #uid
AND
id=10
)

Add filtering on top of Stored Procedure

Currently I am dynamically building a SQL SELECT statement that has filters at the end based on a users selections in three different ListBoxes.
So I end up having...
SELECT
whatever
FROM
dbo.Table
WHERE
(columnA = listB1.Item[x] OR columnA = listB1.Item[y])
AND
(columnB = listB2.Item[g] OR columnA = listB2.Item[h])
....
What I want to do is store the SELECT ... FROM ... as a stored procedure, and then use the remaining WHERE... portion as a parameter I guess.
I tried experimenting in SQL Server Management Studio to see if I could just create a stored procedure with a parameter at the end...
SELECT whatever
FROM dbo.Table #PARAM
... where PARAM = 'WHERE ... and ... or ' and it didn't like that.
Is it possible to grab a stored procedure, open up the actual content of it, and concatenate my WHERE... onto the end of it?
Thanks. I'm no DB expert, so any other ways of doing this would greatly be appreciated.
EDIT: I should add that the AND / OR combination statements are variable.
So one time it could be
SELECT whatever
FROM dbo.TABLE
<no filter>
or
SELECT whatever
FROM dbo.TABLE
WHERE (colA = this)
AND (colB = that)
or
SELECT whatever
FROM dbo.TABLE
WHERE (colA = this OR colA = that OR colA = who)
AND (colC = him)
You can do this by using dynamic queries in stored procedure. Create SP with static select query and pass the where clause as parameter.
CREATE PROCEDURE SP_GetFromDB
(
#Param VARCHAR(200)
)
AS
BEGIN
DECLARE #Query VARCHAR(2000) = ''
SELECT #Query = 'SELECT Column1, Column2, * FROM dbo.MyTable
WHERE ' + #Param
EXECUTE (#Query)
END
In application side, form a string for where clause something like
string query = "(columnA = " + listB1.Item[x] + " OR columnA = " + listB1.Item[y] ") AND (columnB = " + listB2.Item[g] + " OR columnA = " + listB2.Item[h] ")" ;
and pass this as #param for the Stored Procedure.
Create the proc and pass in the users selections as parameters.
CREATE PROCEDURE YourNewSP (x,y,g,h)
as
begin
SELECT whatever FROM dbo.Table
WHERE (columnA = x OR columnA = y)
AND
(columnB = g OR columnA = h)
end
Since SQL Server 2008 you can pass table valued parameters to stored procedures.
So, for each of your list boxes, you could add one table valued parameter.
Then use a WHERE like
WHERE columnA IN(SELECT theValue FROM #listBoxAValues)
AND columnB IN(SELECT theValue FROM #listBoxBValues)
AND columnC IN(SELECT theValue FROM #listBoxCValues)
To get around the case that there are no values provided for any of the three parameters you can pre-check it like
DECLARE #CountA BIT = (SELECT count(*) FROM #listBoxAValues)
DECLARE #CountB BIT = (SELECT count(*) FROM #listBoxBValues)
DECLARE #CountC BIT = (SELECT count(*) FROM #listBoxCValues)
and then rewrite the WHERE like
WHERE (#CountA = 0 OR columnA IN(SELECT theValue FROM #listBoxAValues))
AND (#CountB = 0 OR columnB IN(SELECT theValue FROM #listBoxBValues))
AND (#CountC = 0 OR columnC IN(SELECT theValue FROM #listBoxCValues))
To be able to pass a table valued parameter you have to create a new table valued type in your database first:
CREATE TYPE MyType AS TABLE(theValue int);
Given all your three list boxes could use the same type, your stored procedure would start like
CREATE PROCEDURE dbo.pr_myProc (
#listBoxAValues MyType,
#listBoxBValues MyType,
#listBoxCValues MyType)

Display all records of a table unless I pass a key

Is there an other way to get all rows of a table using a stored procedure unless I pass the procedure a key?
If so, how can I code that in SQL Server?
try this
CREATE PROCEDURE GetData(#key int = null)
BEGIN
SELECT * FROM Table WHERE (#Key Is NULL or id = #Key)
END
You could also use the COALESCE operator:
CREATE PROCEDURE dbo.uspMySprocName(#Key INT = NULL)
AS
BEGIN
SELECT * FROM MyTable WHERE ID = COALESCE(#Key, ID);
END
you can use a if condition and have 2 queries
**syntax:**
if (#key is null ) then
begin
select * from table1 ;
end
else
being
select * from tabel1 where field1 = #key ;
end
endif
The following link should help
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=146620

IF condition in view in SQL Server

Is it possible to have a if condition in VIEWS
eg
CREATE VIEW
as
DECLARE #Count int
SET #Count=-1
select #Count=EmpID from EmployeeDetails where ID=200
IF #Count=-1
BEGIN
SELECT * FROM TEAM1
END
ELSE
BEGIN
SELECT * FROM TEAM1
END
You could try something sneaky with a UNION :
SELECT {fieldlist}
FROM Table1
WHERE EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
UNION ALL
SELECT {fieldlist}
FROM Table2
WHERE NOT EXISTS(SELECT EmpID FROM EmployeeDetails WHERE ID = 200)
This method would require both SELECT statements to return the same set of fields, although their sources might be different.
Views only allow select statements as stated in here
if you need to do if on column values you can use a
SELECT
CASE WHEN COLUMN1 = 1 THEN COLUMNX ELSE COLUMNY END
FROM TABLE1
if your need exceeds this you should create a select from a table valued function instead of a view.
What you need is a simple Procedure
CREATE PROCEDURE DOSOMETHING
(
#ID INT
)
AS
BEGIN
IF #ID > 100
SELECT 1 AS ID,'ME' AS NAME, GETDATE() AS VARIABLEDATECOL, NEWID() AS VARIABLEGUID
ELSE
SELECT 2 AS ID, 'YOU' AS NAME
END
No I don't believe this is possible.
You could use a stored procedure instead to achieve this functionality.
simply use a udf (User defined Function)
Here you can use IF, ELSE, WHILE etc.
But when you are manipulating data (INSERT, UPDATE, DELETE) then you have to use Stored Procedures because udf's aren't able to do that