IF condition in view in SQL Server - sql

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

Related

How can I join different result of a query from a table to another table in a stored procedure

I have tree tables:
Products (Fields: Reference, ...)
InvoiceHeader (Fields: In_No,In-Date,Type, ...)
InvoiceDetails (Reference, Qty, ...)
I want to write a stored procedure which return all the references with the Stock of them.
Invoices are two types: input (which add to stock) and output (which subtract from stock).
It means I have to run a query for two times on InvoiceHeader joining InvoiceDetails on for having inputs of all the references and one for having outputs of the references.
Then I have to join these two queries to the products and make a new field (remain) which minus output from input for each reference.
The results should be like this:
Reference Input Output Remain
X 5 2 3
Y 10 3 7
Z 1 1 0
How can I write the procedure?
Could you please precise what do you would like to know? How to pass 3 values to output, select 3 values, or 'do the job' inside the procedure?
SQL server supports having more than one output value. So If that is your issue you can use for example that blog post which describes how to do that. If your goal is to have procedure which selects these values, but they will not be used in the future you can just... select them in the procedure body... as per below
create procedure as X
begin
select ...
select ...
select ...
end
You can write a procedure with table result set output, like this:
CREATE PROCEDURE my_stored_proc
#param1 INT,
#param2 INT
AS
BEGIN
SELECT T.field1,
T.field2
FROM my_table AS T
WHERE T.field3 = #param1
AND T.field4 = #param2
END
so when executing the procedure, you'd get the result same as executing SELECT statement.
In sql-server (mssql) you can "collect" the output result-set like this:
DECLARE #output1 AS TABLE (field1 INT, field2 INT)
INSERT INTO #output1
EXEC my_stored_proc #param1 = 1, #param2 = 2
you can then use the collected output with any other query, like this:
SELECT T.field2 * 2 + T.field1
FROM #output1 AS T
JOIN some_table6 AS T6 ON T6.id = T.field1

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

Querying different table based on a parameter

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 ...

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

SQL Select Statement including SP Call has syntax error

MYTABLE has ID column. However, following query generates syntax error.
SELECT ID FROM MYTABLE
WHERE ID = EXEC MY_SP ID
What do you think is wrong here?
You can't call stored procedures inline like this.
A couple of options include:
1) Execute the stored procedure and store the results in a temp table. Then use that temp table.
e.g.
CREATE TABLE #Example
(
ID INTEGER
)
INSERT #Example
EXECUTE My_SP
SELECT t.ID FROM MyTable t JOIN #Example e ON t.ID = e.ID
DROP TABLE #Example
2) convert the sproc to a user defined function which you CAN call inline
e.g.
CREATE FUNCTION dbo.MyFunc()
RETURNS TABLE
AS
RETURN
(
SELECT ID FROM SomeTable WHERE ....
)
SELECT t.ID FROM MyTable t JOIN dbo.MyFunc() f ON t.ID = f.ID
3) If the sproc returns a single ID, consider returning an OUTPUT parameter from the sproc instead and use like this:
DECLARE #ID INTEGER
EXECUTE MY_SP #ID OUTPUT
SELECT ID FROM MYTABLE
WHERE ID = #ID
I don't think you need the exec statement, just call the sp, exec is expected to be a separate statement
I don't think you can do that at all. Are you perhaps thinking of a User Defined Function rather than a stored Procedure. Based on the context, you'll need a scalar UDF.
Try this:
SELECT ID FROM MYTABLE WHERE ID = ##SPID