Searching - Stored Procedure - DateTime variable - Easy Resolution? - sql-server-2008

I am trying to create a stored procedure that when entered the three variables:
#Bank_Number = 530
#Branch_Number = 002
#Date_From = 10/28/2014
#Date_To = 10/29/2014
It will return all records between the Date_From and Date_To dates that match the Bank_Number and Branch_Number.
The code I have here is incorrect slightly I'm not sure how to proceed.
ALTER PROCEDURE [dbo].[Something_Proc]
#Bank_Number varchar(3),
#Branch_Number varchar(3),
#Date_From datetime,
#Date_To datetime
AS
BEGIN
SET NOCOUNT ON;
DECLARE #bankNumber varchar(3) = #Bank_Number,
#branchNumber varchar(3) = #Branch_Number,
#dateCreated datetime = #Date_From,
#dateCreated datetime = #Date_To
SELECT DISTINCT
A.bankNumber,
A.branchNumber,
CONVERT(VARCHAR(8), A.dateCreated, 1)
FROM
dbo.(table from picture) A
WHERE
(#bankNumber IS NULL OR Bank_Number LIKE #bankNumber + '%')
AND (#branchNumber IS NULL OR Branch_Number LIKE #branchNumber + '%')
AND (#dateCreated IS NULL OR (MONTH(dateCreated) = MONTH(#dateCreated)
AND DAY(dateCreated) = DAY(#dateCreated)
AND YEAR(dateCreated) = YEAR(#dateCreated)))
END

Can't you just use something like this?
WHERE
(#bankNumber IS NULL OR Bank_Number LIKE #bankNumber + '%')
AND (#branchNumber IS NULL OR Branch_Number LIKE #branchNumber + '%')
AND (#Date_From IS NULL OR #Date_From <= DateCreated)
AND (#Date_To IS NULL OR DateCreated <= #DateTo)
Basically, either your #Date_From and #Date_To parameters are NULL (then that parameters isn't used in any way), or if it's not null, then it's used to compare DateCreated to be equal or larger than #Date_From, and equal or smaller than #Date_To ....

Related

How do I combine the result of two different offset queries

I would like to query a "accounts" table. I'd like to limit the results to include only individuals from the us. See below for what I've tried. It's close but seems to keep sorting everything by Balance instead of CreateDate.
DECLARE #AccountId UNIQUEIDENTIFIER = NULL;
DECLARE #SortBy NVARCHAR(128) = N'CreateDate';
DECLARE #SortDirection VARCHAR(4) = 'DESC';
SELECT [Accounts].[AccountId]
,[Accounts].[Balance]
,[Accounts].[CreateDate]
FROM [dbo].[Accounts]
WHERE [Accounts].[Balance] IS NOT NULL
UNION ALL
SELECT [Accounts].[AccountId]
,[Accounts].[Balance]
,[Accounts].[CreateDate]
FROM [dbo].[Accounts]
WHERE [Accounts].[Balance] IS NULL
)

Column cannot be null - procedure

I am trying to create a procedure in MySQL that insert weeks (for current year) to my week table. But there is a problem because after first row is added for the next one I get an error: number column cannot be null. I am new to MySQL so I will appreciate any help.
CREATE PROCEDURE generateWeeks()
BEGIN
SET #currentYear = YEAR(CURDATE());
SET #nextYear = #currentYear + 1;
SET #startOfCurrentWeek = CURDATE();
WHILE(#currentYear < #nextYear) DO
SET #endOfCurrentWeek = DATE_ADD(#startOfCurrentWeek , INTERVAL 7 DAY);
SET #weekNumber = WEEK(#startOfCurrentWeek, 3) -
WEEK(#startOfCurrentWeek - INTERVAL DAY(#startOfCurrentWeek)-1 DAY, 3) + 1;
INSERT INTO `week` (`number`, `start_date`, `end_date`)
VALUES (#weekNumber, #startOfCurrentWeek, #endOfCurrentWeek);
SET #startOfCurrentWeek = #endOfCurrentWeek + 1;
SET #currentYear = YEAR(#endOfCurrentWeek);
END WHILE;
END //
DELIMITER ;
EDITED:
Table Creation:
CREATE TABLE `week` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`number` INT(11) NOT NULL,
`start_date` DATE NOT NULL,
`end_date` DATE NOT NULL
)
Why for first while iteration everything is ok (rows is added), but in the next one I get null value in #weekNumber variable ?
The line:
SET #startOfCurrentWeek = #endOfCurrentWeek + 1;
will convert the variable into a integer. Use date_add instead.
Also, instead of using user-defined variables (#endOfCurrentWeek) you better use local variabled (declare v_endOfCurrentWeek date).

SSRS String -vs- Data Integer

I am working on a SSRS report and using a parameter that allows you to choose multiple options. However, when I do this I get an error that states:
Error Converting Data Type nVarChar to Int.
The data in the database is an Integer. The parameter is set up as an Integer and it works great when only choosing one option. The issue comes when I choose multiple options.
My co-worker came up with one work-around but I would like something a little more elegant and easier to plug in if possible.
Here is his work-around:
ALTER PROCEDURE [dbo].[DtaPrep_MktgClients]
#BegDate date = NULL
, #EndDate date = NULL
, #Species varchar(50) = 'canine,feline,K9,'
 , #HospList varchar(500) = NULL
This is where the hospmastid string gets converted into a temp table
/*
--===================================--
HOSPITALS SETUP
--===================================--
*/
If #HospList IS NOT NULL
BEGIN
DECLARE #WorkHospList varchar(500)
SET #WorkHospList = #HospList
;
CREATE TABLE #HospList
( HospID smallint NULL )
SET #CommaLoc = charindex(',', #WorkHospList)
WHILE #CommaLoc > 1
BEGIN
SET #curVal = LEFT(#WorkHospList, #commaloc-1 )
INSERT INTO
#HospList( HospID )
SELECT #curVal
SET #WorkHospList = substring( #WorkHospList, #commaloc+1, len(#WorkHospList) )
SET #CommaLoc = charindex(',', #WorkHospList)
END
END
This is using the temp table to accomplish the same thing as a “WHERE Hospmastid IN (101,102,103)…”
Method 1
SELECT
HospitalMasterID
, ClientID
, FirstName
, LastName
FROM
Client
WHERE
HospitalMasterID IN (Select HospID From #HospList )
Needless to say, I am sure there is a better way to accomplish this. If anyone has any ideas, please let me know.
Here is the full Query I am now using. But it is not selecting anything so there is an issue with the Created Table.
USE [xxxxx]
GO
/****** Object: StoredProcedure [dbo].[PriceErosion] Script Date: 11/26/2013 8:26:33 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
-- =============================================
-- Author:
-- Create date: 11/25/2013
-- Description: Determines the products in which the price was lowered and revenue lost during a set time period.
-- =============================================
*/
--#StartDate as Date = Null
--,#EndDate as Date = Null
--,#CurDate as Date = Null
--,#Hospital as VarChar = Null
--,#Division as Int = Null
Declare #StartDate as Date = Null
Declare #EndDate as Date = Null
Declare #Hospital as Int = Null
Declare #Division as Int = Null
DECLARE #curDate Date = Null
SET #curDate = GETDATE()
Set #StartDate = CASE WHEN #StartDate IS NULL THEN DATEADD(dd, -31, Dateadd(dd, -1, #curdate) ) ELSE #StartDate END
Set #EndDate = CASE WHEN #EndDate IS NULL THEN Dateadd(dd, -1, #curdate) ELSE #EndDate END
Set #Hospital = Case When #Hospital IS Null Then '3' Else #Hospital End;
IF OBJECT_ID('tempdb.dbo.#HospList') IS NOT NULL DROP TABLE #HospList ;
If #Hospital IS NOT NULL
BEGIN
DECLARE #WorkHospList varchar(500)
Declare #CommaLoc as Int
Declare #curVal as int
SET #WorkHospList = #Hospital
;
CREATE TABLE #HospList
( HospID smallint NULL )
SET #CommaLoc = charindex(',', #WorkHospList)
WHILE #CommaLoc > 1
BEGIN
SET #curVal = LEFT(#WorkHospList, #commaloc-1 )
INSERT INTO
#HospList( HospID )
SELECT #curVal
SET #WorkHospList = substring( #WorkHospList, #commaloc+1, len(#WorkHospList) )
SET #CommaLoc = charindex(',', #WorkHospList)
END
END
Begin
-- Sets the Baseline Price Date in the PriceChangeHistory Table.
With PC1
as
(Select
HospitalMasterID
,TxnCode
,UserInfoMasterID
,Active
,min(TxnDateTime) as StartingDate
From
PriceChangeHistory
Where
TxnDateTime Between #StartDate and #EndDate
Group By
HospitalMasterID, TxnCode, UserInfoMasterID, Active)
-- Gets the Baseline Price for the period from the PriceChangeHistory Table
,PC
as
(Select
PC1.HospitalMasterID
,PC1.TxnCode
,PC1.UserInfoMasterID
,PC1.Active
,Cast (PC1.StartingDate as Date) as StartingDate
,PC2.OldPrice as StartingPrice
,PC2.NewPrice
,PC2.TxnSubType
From
PC1
Inner Join
PriceChangeHistory as PC2
On
PC1.HospitalMasterID = PC2.HospitalMasterID
and
PC1.TxnCode = PC2.TxnCode
and
PC1.StartingDate = PC2.TxnDateTime
Where
PC2.OldPrice > PC2.NewPrice)
--MedicalHistory Information
,MH
as
(Select
HospitalMasterID
,PatientID
,TxnDate
,TxnCode
,Description
,ListAmount
,ExtendedAmount
,TxnType
,Quantity
,(Case
When Quantity <> '1' Then (ListAmount/Quantity)
Else ListAmount
End) as UnitPrice
From
MedicalHistory
Where
TxnDate Between #StartDate and #EndDate
and
_IsServOrITem = 1)
-- Determines the Revenue lost per each sale, also reduces the results to only those items where the Price was lowered not raised.
,RL
as
(Select
PC.HospitalMasterID
,MH.PatientID
,PC.TxnCode
,PC.TxnSubType
,MH.Description
,PC.UserInfoMasterID as ChangedByUserID
,MH.TxnDate
,PC.StartingPrice
,Cast (MH.UnitPrice as Money) as UnitPrice
,Cast ((StartingPrice - UnitPrice) as Money) as RevenueLost
From
PC
Left OUter Join
MH
on
PC.HospitalMasterID = MH.HospitalMasterID
and
PC.TxnCode = MH.TxnCode
Where
PC.StartingPrice > MH.UnitPrice)
--- Determine the name of the tech changing the prices.
,UI
as
(Select
HospitalMasterID
,UserInfoMasterID
,Name
From
UserInfo)
--- Get the Division and Hospital Name for each Hospital.
,HODI
as
(Select
DI.DivisionID
,DI.DivisionName
,HO.HospMastID
,HO.HospCode
,HO.HospName
From
ref_Hospital as HO
inner Join
ref_Division as DI
on
HO.DivisionID = DI.DivisionID)
,HI
as
(Select
HODI.DivisionID
,HODI.DivisionName
,RL.HospitalMasterID
,HODI.HospCode
,HODI.HospName
,RL.PatientID
,RL.TxnCode
,RL.TxnSubType
,RL.Description
,RL.ChangedByUserID
,RL.TxnDate
,RL.StartingPrice
,RL.UnitPrice
,RL.RevenueLost
From
RL
Left Outer Join
HODI
ON
RL.HospitalMasterID = HODI.HospMastID
Where
TXNDate Between #StartDate and #EndDate)
Select
*
From
HI
Where
HospitalMasterID in (Select HospID from #Hosplist)
Order By
HOspitalMasterID
end
Prior to SQL Server 2008, the standard way to filter by one or more values was to pass an XML document to the Stored Procedure and join on it. In this case, you could pass the data as a string with the integers separated by commas, then convert that into an XML document, then join on the XML. So you should change the multiselect in SSRS to a text datatype. Here's a post that shows you how to open an XML document: http://blog.sqlauthority.com/2009/02/13/sql-server-simple-example-of-reading-xml-file-using-t-sql/
SQL Server 2008 lets you use table-valued parameters, but again, it might be best to pass the data as a string of comma separated integers and then let the stored procedure put the data into a table-valued parameter, and then join on that. Here's a post that describes how to use table valued parameters: http://blog.sqlauthority.com/2008/08/31/sql-server-table-valued-parameters-in-sql-server-2008/

T-SQL IF Block Not Executing Though Conditions Are Met

I've got the following SQL statement that I am working on. I've trimmed it down to the parts necessary to illustrate the problem.
DECLARE #mwareId as int = 9647,
#startDate as datetime = '2011-07-20',
#endDate as datetime = '2011-07-20'
IF OBJECT_ID('tempdb..#tmpInvoiceList', 'U') IS NOT NULL DROP TABLE #tmpInvoiceList
-- Get base invoice list for customer
SELECT invoiceId
,invoiceNumber
,customerId
,customerName
,customerCode
,createDate
,lastModifiedDate
,invoiceDate
,totalInvoiceAmount
,statusId
,isPaid
INTO #tmpInvoiceList
FROM Invoice.Invoice
-- Apply date range if applicable
IF ( #startDate != NULL AND #endDate != NULL )
BEGIN
DELETE FROM #tmpInvoiceList
WHERE invoiceDate NOT BETWEEN #startDate AND #endDate
END
SELECT * FROM #tmpInvoiceList
I have the #startDate and #endDate variables set to date values. The problem is that the if block that applies the date range to the temp table is not executing, though neither of the two variables are null, and I can't find a reason for this.
As far as I'm aware, TSQL doesn't support the != operator for null checks. Try this:
IF ( #startDate IS NOT NULL AND #endDate IS NOT NULL )
IS [NOT] NULL is the right way to compare value with NULL. All of (NULL != NULL) , (1!= NULL), (NULL =NULL) evaluate as NULL(false)
You have to use IS NOT NULL instead of != NULL
IF ( #startDate IS NOT NULL AND #endDate IS NOT NULL )
...

Conversion of date from character string error

I have a select statement which contains a number, description, date. when i try to add my date to the statement and run it i get a date conversion from character string error and i am not really sure how to go about it.
DECLARE #parties AS TABLE (
PartyId UNIQUEIDENTIFIER
, Cases NVARCHAR(MAX)
, CaseTypes VARCHAR(MAX)
, Assignment DateTime)
DECLARE #cases NVARCHAR(MAX)
DECLARE #casetypes VARCHAR(MAX)
DECLARE #assignment DateTime
DECLARE #linebreak AS VARCHAR(2)
SET #cases = NULL
SET #casetypes = NULL
SET #assignment = NULL
SET #linebreak = CHAR(13) + CHAR(10)
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+A.DateOn
FROM [Case] C
INNER JOIN CaseType CT ON C.CaseTypeId = CT.CaseTypeId
INNER JOIN #partyCases PC ON C.CaseId = PC.CaseId
INNER JOIN Appointment A ON C.CaseId = A.CaseId
WHERE PC.PartyId = #partyId
The error occurs after adding A.DateOn to my select statement and running it - any suggestions will be great. Thanks!
SQL returns Date values as datetime and such values can not be implicitly used as strings (varchars). You will have to explicitly convert or cast them. So, change your select statement in either of the 2 ways below:
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+CONVERT(varchar, A.DateOn)
OR
SELECT #cases = COALESCE(#cases+ #linebreak + C.CaseNumber, C.CaseNumber)+"-"+CT.[Description]+"-"+CAST(A.DateOn as varchar)
CONVERT has a slight advantage - you can apply formatting on the date, if you want.