Execute a stored procedure within a case statement - sql

I have an Insert Into Select statement with a Case When clause. I want to execute a stored procedure within the When statement.
Insert into Orders(id, custId, custIntake)
Select id, custId custIntake =
Case
When ( Exec mySProc(custId) = 1 ) = 'InStore'
When ( Exec mySProc(custId) = 0 ) = 'OutsideStore'
Else null
End
From OrdersImport
How can I run Exec mySProc(custId) within the Case When?

I would suggest you convert your 'mySProc' procedure into a Scalar User Defined Function if you want to run it like this. Stored Procedures are not able to do what you want.

If I understand correctly then what you need is code to run when the WHEN statement is true.
Just use CASE > WHEN > THEN as described here: http://msdn.microsoft.com/en-us/library/ms181765.aspx
Hope this helps.

Do like this.
If you set auto increment for id column, not need to mention in the query. If you need, you can add it.
Insert into orders(custId, custIntake)
Select custId, (CASE WHEN custId = '1' THEN 'InsideStore' ELSE 'OutsideStore' END) from ordersimport;
Hope, it will help you.

Related

SQL Server - storing SELECT statement into a variable in a Stored Procedure

In my Stored Procedure, I am trying to store the result of a SELECT statement inside a variable. This is what I have so far:
DECLARE #process_pk uniqueidentifier
INSERT INTO #process_pk
SELECT process_pk
FROM dbo.Process
WHERE process_id = #process_id
In the above, I'm trying to store the result of the SELECT statement into my variable #process_pk, to be used sometime later in the latter part of my stored procedure. But it doesn't seem to be the correct syntax.
I would like to ask what is the correct way to store SELECT statement
results inside a Stored Procedure variable so that it can be used
anytime within the stored procedure.
You should use SET
SET #process_PK = (SELECT process_pk
FROM dbo.Process
WHERE process_id = #process_id)
You can set the value in the SELECT:
SELECT #process_pk = process_pk
FROM dbo.Process
WHERE process_id = #process_id;
This is particularly handy if you want to set multiple values from the same query:
SELECT #process_pk = p.process_pk,
#col1 = p.col1
FROM dbo.Process p
WHERE p.process_id = #process_id;

Parameterized WHERE clause in SQL Server Stored Procedure

I have a Stored Procedure to get the details of Invoices
Some occasions I get the list of invoices by sending only the InvoiceID
But in some other occasions I need to get the list of invoices as per the search fields supplied by the user. To do this I send all the fields to the Stored Procedure and use those parameters as below. I included only 2 columns but there are more.
SELECT * FROM INVOICES I
WHERE
(#InvoiceNumber is null or I.InvoiceNumber = #InvoiceNumber)
and
(#PONo is null or I.PONo = #PONo)
Is there a way to send the condition for the WHERE clause as one parameter?
Yes, it is possible with Dynamic SQL, but I highly discourage to do that.
SELECT * FROM tbl WHERE #condition:
If you are considering to write the procedure
CREATE PROCEDURE search_sp #condition varchar(8000) AS
SELECT * FROM tbl WHERE #condition
Just forget it. If you are doing this, you have not completed the transition to use stored procedure and you are still assembling your
SQL code in the client.
It will also open your application to SQL Injection attacks.
You can use custom type to pass table as parameter https://msdn.microsoft.com/pl-pl/library/bb510489(v=sql.110).aspx or you can use default parameters
If you're using SQL Server 2016 or similar (check by calling select compatibility_level, name from sys.databases and seeing that your DB is 130 or higher) then you can use the string_split builtin function.
I found it works best like this (spread out for clarity)
CREATE PROCEDURE [dbo].[GetInvoices]
#InvoiceNumber int = NULL
#PONo nvarchar(1024) = NULL
AS
SELECT * from [Invoices] AS [i]
WHERE
i.InvoiceNumber = ISNULL(#InvoiceNunber, i.InvoiceNunber)
AND CASE
WHEN #PONo is null
THEN 1
ELSE (CASE
WHEN i.PONo IN (select value from string_split(#PONo, ','))
THEN 1
ELSE 0
END)
END
= 1
So if you pass in a null to either parameter it gets translated as where x = x which is always true, and if you pass in a CSV value, it selects it from a split table of values that, if present, results in the where clause being where 1=1, which is true or 0=1 if the value is not present in the input list.
So here you can pass in an invoice number, or PO number, or both, or neither and it should return what you expect.

T-SQL: WHERE Clause - How to adjust based on input variable

Using SQL Server 2008. I have an input param in my stored proc called '#State'. The param can basically be '--All--' or can contain the state to filter.
So, if it is '--All--' I don't want to incorporate the #State into the where clause. Otherwise I'd like it to filter based on the provided #State. So basically it could result in this....
SELECT * FROM MyTable
WHERE Type='AAA' AND Status=#Status
or, if they pass '--All--'
SELECT * FROM MyTable
WHERE Type='AAA'
How can I do this in a stored proc?
SELECT
*
FROM
MyTable
WHERE
Type='AAA'
AND Status = CASE #Status WHEN '--All--' THEN Status ELSE #Status END
I thought you made a typo. It should be #State, not #Status. This simple query might not be what you are looking for since you want to two sql statements in your requirement.
SELECT * FROM MyTable
WHERE Type='AAA' AND (#State='--All--' or State=#State)
Or...
you could make it even simpler than that:
SELECT * FROM MyTable
WHERE Type='AAA' AND #State in ('--All--', State)
No need to do it in a stored procedure, unless absolutely necessary (or if business/coding practice requires you to do so).

Get the number of affected rows in a MySQL update statement?

I have stored procedure in MySQL, something like the below:
create procedure SP_Test (input1 varchar(20))
begin
update Table1 set Val1='Val' where country=input1;
//I want to see if this update changed how many rows and
//do some specific action based on this number
....
end
How can I determine how many rows were changed by this update?
Use ROW_COUNT():
SELECT ROW_COUNT();
one way, not very optimal is to simply do a select before you do the update.
select count(*) from table1 where country = 'country1'
Try the following code:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )

SQL Query...nulls hosing me

I tried to ask this question before but I don't think I explained myself very well. So here it is: asp.net 2.0 app hitting a SQL 2008 backend. This seems simple but I can't get it. 1 table. The user selects a status. The query should return all records = the chosen status only. If the user select "All Status", then ALL records should be returned, including those with a status = null (which is the part that is hosing me).
Ex:
CASE 1: User selects Status = "Satisfied"; ONLY satisfied records are return
CASE 2: User selects All Status = everything is returned, satisfied AND nulls and anything else
I tried passign in a wildcard but this doesn't return nulls. I tried dynamically buildign the query but I would like to avoid it.
For the case where you want them all, how about: (am I missing something?)
SELECT * FROM <tablename>
SELECT * FROM <tablename> WHERE Status = '*' OR Status IS NULL
...or '%' or whatever wildcard your SQL implementation uses.
...or if you really have no other conditions following this, just select *...
Try this in a stored procedure.
--Pass in #status as a parameter
DECLARE #Status varchar(100)
IF #Status = 'All Status'
BEGIN
SELECT * FROM tablename
END
ELSE
BEGIN
SELECT * FROM tablename where statusfield = #Status
END
One option is
declare #status varchar(50)
SELECT * FROM <tablename> WHERE (#status is null) or (Status = #status)
if you pass null in for the #status parameter then it will return all records. If you pass 'satisfied' or whatever then it will return just those matchng records.
If doing this in SQL 2008, be sure you have SP1 and Cumulative Update 5 installed. Further, I would recommend adding the WITH RECOMPILE option to the procedure. Under those conditions it will be as performant as embedded SQL or even using unions.
See the following article for an indepth discussion of the myriad of ways to perform searching in SQL 2008: Dynamic Search Conditions in T-SQL
The problem is that SQL's = operator always returns NULL when one of the operands is NULL, so using status = '%' indeed doesn't work. The best method is to just not include a condition on status if you want all of them. You can add extra NULL tests to the query, but that again is building it dynamically, I don't see a way to avoid that...
basically your statement will be for 'Statisfied'
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%Statified'
for 'All Status' it will be
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%'
you could use this statment and if selection is 'All Status' then pass a '' for the #status from your UI
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE '%' || #status
Or you can use this one and when you pass the selection from UI make sure it has a '%' (wild char) appended to your status when it not 'All Status'. When its 'All Status' just pass '%' for the #status
SELECT * FROM testtab WHERE
COALESCE(statuscolumn, '') LIKE #status
oh your db is mssql? :) then you will need to replace the collace(statuscolumn, '') with isnull(statuscolumn, '').
Just skip the where clause or the part that is about the status field, example:
SELECT * from table_1 Where status = 'Satisfied'
and
SELECT * from table_1
When you want all records, you have to exclude STATUS from your WHERE clause (or use a UNION and a select statement where STATUS IS NULL).
Depending on what version of SQL you are using, you might be able to use an IF..ELSE... statement.
IF Status='ALL' THEN
... A SELECT statement where STATUS is NOT included in the WHERE
ELSE
... A SELECT statement that has a WHERE with only the status you are looking for
SELECT * FROM <tablename> WHERE isnull(Status,'*') = '*'
Assuming you're passing a variable to an SP:
SELECT * FROM Table WHERE Status CASE #status WHEN 'All status' THEN Status ELSE #status END
Otherwise, you need to concatenate in the selected value within quotes at both places where it currently says #status
The idea is what to do when the users chooses 'All Status'. By setting the param to NULL, you can use the isnull and then each [status] field just needs to equal itself. I've used ISNULL to set to '' to avoid having NULL = NULL>
declare #param_choice varchar(25)
if #param_choice = 'All Status'
Begin
#param_choice = NULL
End
-- get your results
Select * from Some_Table
Where IsNull([Status], '') = IsNull(#param_choice, IsNull([Status], ''))
You'll get the best performance from:
IF #status IS NULL
BEGIN
SELECT t.*
FROM TABLE t
END
ELSE
BEGIN
SELECT t.*
FROM TABLE t
WHERE t.status = #status
END
The next option is to use:
SELECT t.*
FROM TABLE t
WHERE (#status IS NULL OR t.status = #status)
...but that is not sargable.
I do not believe that anyone suggested using a UNION.
SELECT t.*
FROM TABLE t
WHERE (#status IS NULL)
UNION ALL
SELECT t.*
FROM TABLE t
WHERE (t.status = #status)
If #status is NULL, then the first query in the union is executed, and t.status = #status is clearly always false, so the second query in the union is not executed at all.
If #status is not null, then the first query in the union is not exected at all, and the second one is.
Importantly, since ISNULL, COALESCE or a function are not used on t.status or on #status, then if there is an index on status, it can be used. That is, the predicate is SARGABLE.
And I used UNION ALL (instead of UNION) to prevent a SORT and DISTINCT operation that can be very slow.