If Else Statement in SQL Server stored procedure - sql

In SQL Server, on .NET you can add together a SQL statement and therefor use either 'or' or 'and'.
I am stuck how to do this in a SQL Server stored procedure.
Question:
What is it called what you add together SQL statements? I have a feeling it starts with a 'c' concocations??
I believe I am close with the below code to having a 'variable' SQL?
Code:
BEGIN
SELECT *
FROM TblEmployee
WHERE
FirstName LIKE '%' + LTRIM(RTRIM((#sFirstName))) + '%'
or
Surname LIKE '%' + LTRIM(RTRIM((#sSurname ))) + '%'
and
IF (LTRIM(RTRIM((#sOfficeBase))) = 'xyz1234')
and OfficeBase = LTRIM(RTRIM((#sOfficeBase)))
ELSE
or
OfficeBase= LTRIM(RTRIM((#sOfficeBase)))
END
There are simular queries such as If else in stored procedure sql server
But I have a feeling I searching for the 'wrong' question. Thanks in advance

The where clause allows you to embed conditional logic - you don't need if/then/else, which is just as well, because afaik, that's not supported by any SQL dialect in a where clause.
BEGIN
SELECT *
FROM TblEmployee
WHERE
FirstName LIKE '%' + LTRIM(RTRIM((#sFirstName))) + '%'
or
Surname LIKE '%' + LTRIM(RTRIM((#sSurname ))) + '%'
and
(OfficeBase = 'xyz1234'
or
OfficeBase= LTRIM(RTRIM((#sOfficeBase)))
END

I am pretty sure you have some missing parenthesis in your original query. Not sure why you are adding LTRIM and RTRIM to your parameters. Taking a shot in the dark I suspect you could boil down your query to this.
SELECT * --This should be the column names actually needed, * is not good for production code
FROM TblEmployee
WHERE
(
FirstName LIKE '%' + #sFirstName + '%'
or
Surname LIKE '%' + #sSurname + '%'
)
and OfficeBase in ('xyz1234', #sOfficeBase)

Related

Can you use a parameter to reference a column in a select statement?

I am trying to reference a table column based on a parameter. The last line of my where clause is
'GRAD_' +LEFT(#REPORTING_DATE-20000,4) LIKE '%' + #PROGRAM + '%'
I hoping to get my the code to look like GRAD_2018 LIKE '%BIOL%' but when I run the code I get a '0' in the result set where I know I should be getting 18.
Below is my sample code
DECLARE
#REPORTING_DATE INT,
#PROGRAM VARCHAR(4)
SET #REPORTING_DATE = '20201101'
SET #PROGRAM = 'BIOL'
SELECT COUNT(ID)
FROM PROGRAM_DATA
WHERE PROGRAM LIKE '%' + #PROGRAM + '%' AND REPORT_DATE IN (#REPORTING_DATE-60000) AND
'GRAD_' +LEFT(#REPORTING_DATE-20000,4) LIKE '%' + #PROGRAM + '%'
I am using MSSQL and SSRS.
Unfortunately, you can't reference fields like that. You would need to use dynamic SQL to do this.
You build the SQL as a string and then EXECUTE it.
DECLARE #SQL VARCHAR(8000)
SET #SQL ='
SELECT COUNT(ID)
FROM PROGRAM_DATA
WHERE #PROGRAM LIKE ''%' + #PROGRAM + '%''
AND REPORT_DATE IN (''' + #REPORTING_DATE-60000 + ''')
AND GRAD_' + LEFT(#REPORTING_DATE-20000,4) + ' LIKE ''%''' + #PROGRAM + '''%''
'
EXEC(#SQL);
Another way to do this in SSRS is by creating your dataset from an expression.
In this example, I've assumed you actually want to pass the variable values from report parameters.
Create parameters to hold you two variables, called pReportDate and pProgram.
In the dataset properties, click the expression button against the query [fx] .
Make sure you include the equal sign and set the whole sql statement in quotes something like.
="
SELECT COUNT(ID)
FROM PROGRAM_DATA
WHERE PROGRAM LIKE '%" & Parameters!pProgram.Value & "%' AND REPORT_DATE IN (" & Parameters!pReportDate.Value & "-60000) AND
'GRAD_' +LEFT(&" Parameters!pReportDate.Value &"-20000,4) LIKE '%" & Parameters!pProgram.Value & "%'"
I've also assumed that #PROGRAM was a typo in the first part of your where clause.
The drawback with this approach is the you will probably have to manually add all the query fields to the dataset as SSRS may not be able to detect them automatically.
One more thought... since a table generally has a fixed number of columns, have you considered writing your where clause to simply spell out all of the columns with 'and' or 'or' as applies to your case?

Oracle to SQL Server conversion

What is the equivalent of SQL Server query form for the below Oracle query in a LIKE statement:
((UPPER(ADDRESS) like '%'|| UPPER(:VALUE1) || '%' ) OR (ADDRESS IS NULL AND :VALUE1 IS NULL))
I am stuck with the syntax '%'||------||'%'.
|| is Oracle's concatenation operator. SQL Server's equivilent is +.
((UPPER(ADDRESS) like '%' + UPPER(#VALUE1) + '%' )
OR (ADDRESS IS NULL AND #VALUE1 IS NULL))
Incidentally, || is the SQL standard, + is used by some databases, like SQL Server instead of following the standard.
((UPPER(ADDRESS) like '%' + UPPER(VALUE1) + '%' ) OR (ADDRESS IS NULL AND VALUE1 IS NULL))
Note that using upper is only necessary depending on the collation setting.
You can use + instead of || to concatenate the strings
((UPPER(ADDRESS) like '%'+ UPPER(VALUE1) + '%' ) OR (ADDRESS IS NULL AND VALUE1 IS NULL))
You also do not need to use upper in comparison for SQL Server. Comparisons in SQL Server are case insensitive.
Is this part of a where clause or something?

WHERE clause with OR operator not giving intended result

I want to write a stored procedure for a search function. I have a database of movies and I should be able to search a movie by Movie.Name, Movie.Producer, Movie.Director and appearing Cast.Name.
CREATE PROCEDURE RetrieveSearchResults
#tokenParam VarChar
AS
Select *
from
(Movie
join
Cast on Movie.MovieID = Cast.MovieID)
join
Actor on Actor.ActorID = Cast.ActorID
where
(Movie.Name like '%' + #tokenParam + '%')
or (Movie.Producer like '%' + #tokenParam + '%')
or (Movie.Director like '%' + #tokenParam + '%')
or (Actor.Name like '%' + #tokenParam + '%')
Upon execution
RetrieveSearchResults 'Almighty'
I get almost all tuples with no similar literal as 'Almighty'
Am I missing something?
Try declaring the varchar limit. VARCHAR(100) or something like that. It may be making assumptions on the length and cutting it down to a VARCHAR(1) or similar. The problem with declaring VARCHAR without a length is the system will assign for you and it may not be what you expect.

Oracle LIKE-wildcard in inner SELECT query

In SQL Server T-SQL I used to use the scenario like this
SELECT .. FROM .. WHERE sometable.eng LIKE (SELECT tmpcolumn FROM tmptable WHERE tmpID = #counter) + '%';
How to pass LIKE (subquery) + '%' in Oracle correcly?
Does it actually work for Oracle 11g+ or not?
.. smth LIKE (SELECT .. FROM ..) + '%';
The underscore _ for fixed length doesn't fit my needs, so % only.
Oracle uses || for string concatenation, not +. So it should be:
smth LIKE (SELECT .. FROM ..) || '%'
This seems like such an odd formulation. Just as a note, I would write the query as:
SELECT ..
FROM ..
WHERE EXISTS (SELECT 1
FROM tmptable
WHERE tmpID = #Counter AND
sometable.eng LIKE tmpcolumn || '%'
);
Putting a subquery between the keyword LIKE and the wildcard makes the query harder to read (at least for me).

SQL Search Query With Null and ''

I have a query that I'm building for an application. The database is setup in SQL Server 2008. I want to use a query similar to below, however, I will be using this 'Where' clause for about 4 other columns using the same requirements. Is this the appropriate way to test for null or '' in a column that is VarChar(255) and does allow nulls.
Ideally, if the variable #UutSerialNumber is null or empty (''), I want all the results, but if it is not, I want to use the 'LIKE' clause. Is this the proper way of doing this and will it work? It seems to work until I start adding more columns to the Where clause.
Also, how would I handle a "text" datatype using the same type of query?
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%' OR UutSerialNumber LIKE '%%' AND (#UutSerialNumber = '' OR #UutSerialNumber IS NULL)) AND ...
Help is appreciated. Thanks everyone!
It amy seem like duplication of SQL but the best way to do this is in terms of performace is using IF ... ELSE
IF ISNULL(#UutSerialNumber, '') = ''
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
-- MORE EXPRESSIONS
END
ELSE
BEGIN
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (UutSerialNumber LIKE '%' + #UutSerialNumber + '%'
-- MORE EXPRESSIONS
END
It can be done within the WHERE clause if you are doing it on multiple columns and the query you posted wasn't far off it was just missing additional parenthesis along with having a redundant clause.
SELECT DeviceName, UutStatus
FROM MyTable
WHERE (ISNULL(#UutSerialNumber, '') = '' OR UutSerialNumber LIKE '%' + #UutSerialNumber + '%')
AND (ISNULL(#AnotherParameter, '') = '' OR AnotherColumn LIKE '%' + #AnotherParameter + '%')
Convert the text type to VARCHAR(MAX).
as a footnote, I personally would use the CHARINDEX rather than concatenating strings in the like:
WHERE (ISNULL(#UutSerialNumber, '') = '' OR CHARINDEX(#UutSerialNumber, UutSerialNumber) > 0)
This is nothing more than a footnote however as I have done no performance testing, I just think it is easier on the eye!
SELECT DeviceName, UutStatus
FROM MyTable
WHERE ((#UutSerialNumber = '') OR (#UutSerialNumber is null)) OR (UutSerialNumber like #UutSerialNumber)
add '%' to the last #UutSerialNumber if you think you need