Condition WHERE clauses inside stored procedure - sql

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

Related

How to put IF condition in where section of select command in 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)

MSSQL Stored Procedure with dynamically added WHERE?

I have this Stored Procedure, where i need to check if #DateChk == 1, THEN i want to add a WHERE-clause to the SQL statement in the SP. If its 0, there should not be any WHERE-clause.
How do i script such function? In a program i could just build in the string to pass to the server, but i have not found any way to do this in the SQL server.
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
SELECT CASE #DateChk
WHEN 1: WHERE dateDay BETWEEN '2016-08-01' AND '2016-08-31'
Something like this, if #DateChk = 1, the WHERE should be added, else fetch all records.
You can modify your condition like this:
SELECT dateDay, SUM(nok) as NOK, SUM(ok) as OK, (SUM(ok) + SUM(nok)) as 'Total'
FROM #st
WHERE
(#DateChk = 1 and (dateDay BETWEEN '2016-08-01' AND '2016-08-31'))
or #DateChk = 0
And it will exactly match your desired behaviour: condition on dateDay will be applied only when #DateChk = 1.

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.

SQL function not working properly, but does when not as a function

I'm having another issue with a SQL Function that I had written. If I run it not in a function and use declared variables, then it works perfectly. But as soon as I put it into a function and run it, nothing appears, its empty.
I cannot put this into a stored procedure, it needs to be in a function.
the code is
select * from [MYTABLE]
where MajorGroupID = #MajorGroupID
and ((#Status = 0 and (
Inactive = 0)
))
or MajorGroupID = #MajorGroupID and (#Status = 1 and (Inactive = 0 or Inactive = 1))
I am not really familiar with functions, I can do basic things with functions but when it comes to adding logic to it. If I was allowed to use stored procedures then I wouldn't be having problems.
This is MSSQL and using SQL Server 2010.
EDIT, Added complete function
CREATE FUNCTION [dbo].[WT_FN_GET_MYTABLE_By_MajorGroupID_Inactive]
(
#MajorGroupID varchar,
#Status int
)
RETURNS TABLE
AS
RETURN
select * from [MYTABLE]
where MajorGroupID = #MajorGroupID
and ((#Status = 0 and (
Inactive = 0)
))
or MajorGroupID = #MajorGroupID and (#Status = 1 and (Inactive = 0 or Inactive = 1))
You don't provide a length for #MajorGroupID varchar, so it is going to be 1 by default, at which point it will not find anything in the table.
Provide a length, e.g. #MajorGroupID varchar(30).