Conversion of date from character string error - sql-server-2008

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.

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
)

Conversion failed when converting the nvarchar value '2151','1886' to data type int

I have the below query
DEClare #Plan_ID nvarchar(100)
set #Plan_ID=REPLACE('2151,1886',',',''',''')
and
SELECT distinct Plan_Dict_Id from REF_Plan_Dictionary WHERE
CAST(Plan_Dict_Id as int) in (#Plan_ID),
Pls help , Plan_Dict_Id datatype is INT, I want to pass the values to where , but getting error "Conversion failed when converting the varchar value '2151','1886' to data type int."
If this is one of the later versions of SQL Server then you could do something like this...
DECLARE #Plan_ID nvarchar(100)
SET #Plan_ID= '2151,1886'
SELECT DISTINCT Plan_Dict_Id
FROM REF_Plan_Dictionary d
JOIN string_split(#Plan_ID, ',') s ON d.Plan_Dict_Id = s.[value]
If you are using an older version you could put the whole statement in a string and then execute it, however you have a problem in your first line as you are not adding quotes around the string... I've accounted for that below.
DEClare #Plan_ID nvarchar(100) set #Plan_ID=REPLACE('2151,1886',',',''',''')
DECLARE #sql nvarchar(max)
SET #SQL = 'select distinct Plan_Dict_Id from REF_Plan_Dictionary where CAST(Plan_Dict_Id as int) in (''' + #Plan_ID + ''')'
EXEC (#sql)

What is the error in mysql procedure I am Getting Error in my code is anyone

BEGIN
DECLARE i INT DEFAULT 0;
DECLARE J INT DEFAULT 0;
DECLARE msg varchar(255) DEFAULT null;
DECLARE msg1 varchar(255) DEFAULT null;
DECLARE s VARCHAR(255) DEFAULT null;
set i = select em_DOJ
from employee_master
where MONTH(em_DOJ) = MONTH(NOW()) and DAY(em_DOJ) = DAY(NOW());
set j = (select TIMESTAMPDIFF(year,i,now()));
set msg1 = 'Congrats';
set msg = concat(msg1, j, 'Years Completed');
INSERT INTO time_line( tl_name, tl_dob, tl_message)
select em_first_name, em_DOJ, msg
from employee_master;
end
Why am I getting errors for this code. My intention is to transfer data from one table to another and to calculate the year at the same time. I am getting the error in this line.
set i = select em_DOJ
from employee_master
where MONTH(em_DOJ) = MONTH(NOW()) and DAY(em_DOJ) = DAY(NOW());
Thanks For Solution.
You don't have a WHERE clause in the INSERT ... SELECT ... query, so it's selecting all rows from employee_master, and inserting a row into time_line for each of them with msg.
You don't need multiple queries. You should combine them all into a single SELECT so that the number of years in the message matches that employee.
INSERT INTO time_line (tl_name, tl_dob, tl_message)
SELECT em_first_name, em_DOJ,
CONCAT('Congrats on ', TIMESTAMPDIFF(year, em_DOJ, ,now()), ' Years Completed')
FROM employee_master
WHERE MONTH(em_DOJ) = MONTH(NOW()) and DAY(em_DOJ) = DAY(NOW());
You need to wrap the SELECT with braces:
set i = (select em_DOJ
from employee_master
where MONTH(em_DOJ) = MONTH(NOW()) and DAY(em_DOJ) = DAY(NOW()));
Additionally, this select does potentially return more than one result which would then cause an error.

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/

Using a parameter in UDF from clause

I have a User defined function in SQL Server 2008. Here it is:
CREATE FUNCTION [dbo].[GetAddressByEntityNameAndId]
(
-- Add the parameters for the function here
#entityName varchar (100),
#parentEntityId int
)
RETURNS varchar(300)
AS
BEGIN
-- Declare the return variable here
DECLARE #Address varchar(300)
if(#entityName = 'Staff')
BEGIN
select #Address = ca.Address + ' ' + ca.City + ' ' + ca.State + ' ' + ca.ZipCode
from #entityName cc
inner join ContactAddress ca on ca.ParentEntityId = cc.Id
inner join EntityName en on en.Id = ca.EntityNameId and en.Name = #entityName
inner join GeneralLookup gl on ca.glAddressTypeId = gl.Id and gl.LookupItem = 'Primary'
where cc.Id = #parentEntityId
END
-- Return the result of the function
RETURN #Address
END
But it does not get executed. Error message is:
Must declare the table variable "#entityName".
Any help would be appreciated.
UPDATE:
Ok now I have another problem. This is my SP:
ALTER PROCEDURE [dbo].[spGetStaffsAndClients]
AS
BEGIN
declare #Address varchar (100)
declare #Apartment varchar (100)
declare #City varchar (100)
declare #State varchar (10)
declare #Zip varchar (10)
declare #County varchar (100)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
/* Get Client's Residence */
select dbo.GetClientFullName(s.FirstName, s.MiddleInit, s.LastName) StaffName,
dbo.GetStaffTitlesById(s.Id) StaffTitle,
dbo.GetClientFullName(c.FirstName, c.MiddleInit, c.LastName) ClientName,
dbo.GetAddressByEntityNameAndId('Client', c.Id) ClientAddress
from ClientStaff cs
left outer join Staff s on cs.StaffId = s.Id
left outer join Client c on cs.ClientId = c.Id
END
This is UDF:
ALTER FUNCTION [dbo].[GetAddressByEntityNameAndId]
(
-- Add the parameters for the function here
#entityName varchar (100),
#parentEntityId int
)
RETURNS varchar(300)
AS
BEGIN
-- Declare the return variable here
DECLARE #Address varchar(300)
if(#entityName = 'Client')
BEGIN
select #Address = ca.Address + ' ' + ca.City + ' ' + ca.State + ' ' + ca.ZipCode
from Client cc
inner join ContactAddress ca on ca.ParentEntityId = cc.Id
inner join EntityName en on en.Id = ca.EntityNameId and en.Name = cc.Id
inner join GeneralLookup gl on ca.glAddressTypeId = gl.Id and gl.LookupItem = 'Primary'
where cc.Id = #parentEntityId
END
-- Return the result of the function
RETURN #Address
END
I am executing the SP and getting error:
Conversion failed when converting the varchar value 'Client' to data type int.
I am unable to sort out the problem. Any help ?
You can't use #entityName in the from clause instead of a table name. Since you only test on Staff you can use from Staff cc instead. The only way I know of to have a variable table name in the from clause is to use dynamic SQL. And I don't think you can use dynamic SQL in functions.
Read more about dynamic queries here http://www.sommarskog.se/dynamic_sql.html.