How to put IF condition in where section of select command in SQL? - sql

I declare some filters on a form and pass them into my SP in SQL for running a select command and this is how I did that, but it didn't work:
DECLARE #Confirm_Filter AS BIT=NULL,
#ReciveDate_Filter AS NCHAR(10) = NULL
....
select * from .......
where
(#Confirm_Filter IS NOT NULL AND InterviewConfirm = #Confirm_Filter)
AND
(#ReciveDate_Filter IS NOT NULL AND ReciveDate BETWEEN GETDATE() AND #ReciveDate_Filter)
and in the where section I want to do:
where
if #Confirm_Filter IS NOT NULL Then (Select * from ... where InterviewConfirm = #Confirm_Filter)
AND
if #ReciveDate_Filter IS NOT NULL Then (select * from .... where ReciveDate BETWEEN GETDATE() AND #ReciveDate_Filter)
and I know above form is totally mistake but how could I do it?

Your problem is called dynamic search conditions. It is solved either by using dynamic SQL, or the following pattern (which is similar to your first version, but with a few changes):
select * from .......
where
(#Confirm_Filter IS NULL OR InterviewConfirm = #Confirm_Filter)
AND
(#ReciveDate_Filter IS NULL OR ReciveDate BETWEEN GETDATE() AND #ReciveDate_Filter)

Related

Scalar variable issue not being able to use in Select Query SQL Server

I 'm not able to use both Declare statements in my select query when I do the insert into.
How do you use a column itemId to be set in a another column called id?
How do you write a same string to a specific column?
Why can't I call my scalar variable ?
DECLARE #Solutions_id as INT
DECLARE #Solutions_name as nvarchar(50)
INSERT INTO ticket_historical_actions
(
[id]
,[type]
[Solutions _rowId]
,[Solutions_dw_dateCreate]
,[Solutions_dw_dateMod]
,[Solutions_dw_dateDelete]
,[Solutions_sourceId]
,[Solutions_date_create]
,[Solutions_date_mod]
,[Solutions_date_approval]
,[Solutions_itemId]
,[Solutions_solutionTypeName]
,[Solutions_content_plainText]
,[Solutions_userId]
,[Solutions_userId_editor]
,[Solutions_userId_approval]
,[Solutions_userName]
,[Solutions_userName_approval]
,[Solutions_status]
,[Ticket_rowId]
,[Ticket_dw_dateCreate]
,[Ticket_dw_dateMod]
,[Ticket_dw_dateDelete]
,[Ticket_sourceId]
,[Ticket_date_create]
,[Ticket_date_mod]
,[Ticket_date_close]
,[Ticket_date_solve]
,[Ticket_entityId]
,[Ticket_name]
,[Ticket_date]
,[Ticket_status]
,[Ticket_is_deleted]
,[Ticket_content_PlainText]
,[Ticket_type]
,[Ticket_urgency]
,[Ticket_impact]
,[Ticket_priority]
,[Ticket_requestTypeId]
,[Ticket_userId_lastUpdater]
,[Ticket_userId_recipient]
,[Ticket_time_to_resolve]
,[Ticket_time_to_own]
,[Users_rowId]
,[Users_dw_dateCreate]
,[Users_dw_dateMod]
,[Users_dw_dateDelete]
,[Users_sourceId]
,[Users_date_create]
,[Users_date_mod]
,[Users_name]
,[Users_LastName]
,[Users_firstName]
,[Users_phone]
,[Users_mobile]
,[Users_language]
,[Users_profileId]
,[Users_entitieId]
,[Users_titleId]
,[Users_categoryId]
,[Users_managerId]
,[Company_rowId]
, [Company_dw_dateCreate]
,[Company_dw_dateMod]
,[Company_dw_dateDelete]
,[Company_sourceId]
,[Company_date_mod]
,[Company_date_create]
,[Company_completename]
,[Company_name]
,[Company_address]
,[Company_postcode]
,[Company_town]
,[Company_state]
,[Company_country]
,[Company_phonenumber]
,[Company_email]
,[Company_admin_email]
,[Company_admin_name]
)
SELECT
#Solutions_id =[itemId], #Solutions_name = 'Solutions',
ts.[rowId]
,ts.[dw_dateCreate]
,ts.[dw_dateMod]
,ts.[dw_dateDelete]
,ts.[sourceId]
,ts.[date_create]
,ts.[date_mod]
,ts.[date_approval]
,ts.[itemId]
,ts.[solutionTypeName]
,ts.[content_plainText]
,ts.[userId]
,ts.[userId_editor]
,ts.[userId_approval]
,ts.[userName]
,ts.[userName_approval]
,ts.[status]
, tt. [rowId]
,tt.[dw_dateCreate]
,tt.[dw_dateMod]
,tt.[dw_dateDelete]
,tt.[sourceId]
,tt.[date_create]
,tt.[date_mod]
,tt.[date_close]
,tt.[date_solve]
,tt.[entityId]
,tt.[name]
,tt.[date]
,tt.[status]
,tt.[is_deleted]
,tt.[content_PlainText]
,tt.[type]
,tt.[urgency]
,tt.[impact]
,tt.[priority]
,tt.[requestTypeId]
,tt.[userId_lastUpdater]
,tt.[userId_recipient]
,tt.[time_to_resolve]
,tt.[time_to_own]
, tu.[rowId]
,tu.[dw_dateCreate]
,tu.[dw_dateMod]
,tu.[dw_dateDelete]
,tu.[sourceId]
,tu.[date_create]
,tu.[date_mod]
,tu.[name]
,tu.[LastName]
,tu.[firstName]
,tu.[phone]
,tu.[mobile]
,tu.[language]
,tu.[profileId]
,tu.[entitieId]
,tu.[titleId]
,tu.[categoryId]
,tu.[managerId]
, tc. [rowId]
,tc.[dw_dateCreate]
,tc.[dw_dateMod]
,tc.[dw_dateDelete]
,tc.[sourceId]
,tc.[date_mod]
,tc.[date_create]
,tc.[completename]
,tc.[name]
,tc.[address]
,tc.[postcode]
,tc.[town]
,tc.[state]
,tc.[country]
,tc.[phonenumber]
,tc.[email]
,tc.[admin_email]
,tc.[admin_name]
FROM
ticket_ticketSolutions ts
left join ticket_tickets tt
on ts.itemId =tt.sourceId
left join ticket_users tu
on ts.userId = tu.sourceId
left join ticket_company tc
on tu.entitieId = tc.sourceId
Would tell me if possible how to do it?
Thank you very much.
I'm just going to answer, even though I have stated this in the comments of both your questions.
The problem here is you are trying to assign a value to your variables in the same statement you are trying to return a dataset; in T-SQL that in not allowed.
In short, you have something like this:
SELECT #MyVariable = SomeColumn,
AnotherColumn
FROM dbo.YourTable
WHERE ID = 'SomeID';
So you want to return the value of AnotherColumn to the presentation layer, but assign the value of SomeColumn to the variable #MyVariable; you can't do this.
Instead, you have to use 2 statements:
SELECT #MyVariable = SomeColumn --Assigns the value to #MyVariable
FROM dbo.YourTable
WHERE ID = 'SomeID';
SELECT AnotherColumn --Returns the dataset to the presentation layer
FROM dbo.YourTable
WHERE ID = 'SomeID';

How to set optional parameter for int type variable

Have two variable StatusTypeTestID and StatusTestID want to set them as optional in where clause as like bellow,but optional option not work for int variable.
Note: default value for int variable is 0
DECLARE #StatusTypeTestID as int
SET #StatusTypeTestID = 1
DECLARE #StatusTestID as int
SET #StatusTestID = 0
select *
from LiveCustomerStatus
where (StatusType=#StatusTypeTestID
and (Status = #StatusTestID or #StatusTestID is null))
As you were already trying, you can check if your parameters have been set as null or if they match the correspondent field.
This way you can leave a parameter as null if you want it to be optional, not affecting the result.
select *
from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
option(recompile)
I have added a option(recompile) clause that will force SQL Server to recompile the query at every execution. This way it will use the appropriate indexes to optimize it depending of the value of the parameters (wether they are null or not).
You can comment both set statements and below query will work:
select * from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
Use CASE Statement in WHERE clause :
SELECT *
FROM LiveCustomerStatus
WHERE StatusType = CASE WHEN ISNULL(#StatusTypeTestID,'') = '' THEN
StatusType ELSE #StatusTypeTestID END
AND Status = CASE WHEN ISNULL(#StatusTestID,'')= '' THEN Status ELSE
#StatusTestID END

Extracting a portion of a value out of a database column using SQL server

I'm trying to extract a portion of a value out of a database column using SQL server.
The example below works in a simple context with a varchar field. The result is: &kickstart& which is what I want.
I now want to do the same when retrieving a column from the database.
But SQL does not like what I am doing. I'm thinking it is something easy that I am not seeing.
Declare #FileName varchar(20) = '&kickstart&.cfg'
Declare #StartPos integer = 0
Declare #FileNameNoExt varchar(20)
SELECT #FileNameNoExt = Left(#FileName,( (charindex('.', #FileName, 0)) - 1))
SELECT #FileNameNoExt
Here is the SQL statement that I can't seem to get to work for me:
Declare #FileNameNoExt as varchar(20)
SELECT
i.InstallFileType AS InstallFileType,
o.OSlabel AS OSLabel,
SELECT #FileNameNoExt = (LEFT(oi.FIleName,( (charindex('.', oi.FIleName, 0) ) - 1) )) AS FileNameNoExt,
oi.FIleName AS FIleName
FROM
dbo.OperatingSystemInstallFiles oi
JOIN dbo.InstallFileTypes i ON oi.InstallFileTypeId = i.InstallFileTypeId
JOIN dbo.OperatingSystems o ON oi.OperatingSystemId = o.OperatingSystemId
Why do you need the variable at all? What's wrong with:
SELECT
i.InstallFileType AS InstallFileType,
o.OSlabel AS OSLabel,
LEFT(oi.FIleName,( (charindex('.', oi.FIleName, 0) ) - 1) ) AS FileNameNoExt,
oi.FIleName AS FIleName
FROM
dbo.OperatingSystemInstallFiles oi
JOIN dbo.InstallFileTypes i ON oi.InstallFileTypeId = i.InstallFileTypeId
JOIN dbo.OperatingSystems o ON oi.OperatingSystemId = o.OperatingSystemId
You've put a SELECT inside another SELECT list without nesting, which is a syntax error in SQL Server.
You are also attempting to assign a variable while performing a data-retrieval operation. You can select all data to be shown, or all data into variables but not both at the same time.
When the two issues above are resolved, I think you may still run into issues when committing filenames into a variable which only allows 20 characters - but then I don't know anything about your dataset.

Set Date from another table in SQL Server

I have a code in VB.Net application which I would like to move to stored procedure.
VB code looks something like this :
if(id == 3)
{
var year = Year(invoiceDate)
updatedDate = DateSerial(dueYear, DueDateMonth, DueDateDay)
If updatedDate < invoiceDate Then
updatedDate += 1
updatedDate = DateSerial(updatedDate , getMonthFromDBTable, getDayFromDBTable)
End If
}
This is part of a condition which I am trying to resolve.
Currently in SQL I have the following
DECLARE #tmpCalendarDate DATETIME;
DECLARE #tmpYear int;
SET #tmpCalendarDate = convert(varchar(10), getdate(),120);
SET #tmpYear = DATEPART(yyyy, #tmpCalendarDate);
SELECT COALESCE (
CASE WHEN tt.ID = 1 THEN DATEADD(day, t.DaysUntilDue, r.InvoiceDate) END,
CASE WHEN tt.ID = 3 THEN -- This is where I need to add the condition.
I was thinking of setting the #tmpCalendarDate with the values to look something like
CASE WHEN tt.ID = 3 THEN #tmpCalendarDate = '#tmpYear-t.DueDateMonth-t.DueDateDay'
where t is a table.
This value cannot be changed, so I would rather calculate and fetch it once rather than calculating it every time binding changes (wpf application).
Any help is greatly appreciated.
UPDATE: I realized maybe I am vague with my question, so here it is
How do i set #tmpCalendarDate? I tried
SELECT #tmpCalendarDate = '#tmpYear-t.DueDateMonth-t.DueDateDay' FROM table t
and I get an error 'Conversion failed when converting date and/or time from character string.' Instead I am expecting something like #tmpCalendarDate to be set to '2016-03-12'
Also, can I add an If..Else condition inside CASE.Then
In my example:
CASE WHEN tt.ID = 3 THEN #tmpCalendarDate = '#tmpYear-t.DueDateMonth-t.DueDateDay'
IF (#tmpCalendarDate > InvoiceDate)
BEGIN
--Do some logic
END
ELSE
--Do some logic
BEGIN
END
You can use DATEFROMPARTS
#tmpCalendarDate = DATEFROMPARTS(#tmpyear, t.DueDateMonth, t.DueDateDay)
Your mistake in your original attempt is you are setting #tempCalendarDate to actual string #tmpYear-t.DueDateMonth-t.DueDateDay which results in a conversion error.

Condition WHERE clauses inside stored procedure

I am working with a stored procedure where I want to add or remove WHERE clauses according to the values of a couple parameters.
This is what I've got so far:
WHERE
t.iDdPais = #iIdPais
AND t.iIdRegion = #iIdRegion
AND t.dtFecha BETWEEN #dtStart AND #dtEnd
BUT, if #iIdPais is 0 (which means ALL), I need to remove that clause from the WHERE statement, the same goes to #iIdRegion.
Put the entire SELECT inside IF clause..
IF(#ildPais =0 AND #ildRegion =0)
SELECT <THE DATASET> FROM THE TABLE
WHERE
t.iDdPais = #iIdPais
AND t.iIdRegion = #iIdRegion
AND t.dtFecha BETWEEN #dtStart AND #dtEnd
ELSE
SELECT <THE DATASET> FROM THE TABLE
--no where clause
You just need to use normal boolean logic:
WHERE
(#iIdPaid = 0 OR t.iDdPais = #iIdPais)
AND (#iIdRegion=0 OR t.iIdRegion = #iIdRegion)
AND t.dtFecha BETWEEN #dtStart AND #dtEnd