T-SQL Procedure not working, issue with varchar to date conversion - sql

When I run this SP, I get:
Msg 241, Level 16, State 1, Procedure PED_SP_PED_Updates, Line 22
Conversion failed when converting date and/or time from character string.
Here is the execution:
exec dbo.ped_sp_ped_updates
#CURRENTHICN='111111111A',
#DATERECEIVED = '20140904',
#FIELDTOBECHANGED='FIRST_NAME_MEMBER',
#CURRENTFIELDVALUE = 'MARY',
#NEWFIELDVALUE = 'MARYTEST',
#REQUESTEDBY = 'IPISORS',
#ID=156
I am not sure why, I'm casting the varchar back to a date for the comparison.
Please note, I have no problem being told a better way to do it, but it would be (I think) more helpful to my learning if I could, at least 'also', get a direct answer as to why my current proc isn't working. In addition to any helpful ideas as to why it should be done different, better, etc, etc. etc.
ALTER PROCEDURE [dbo].[PED_SP_PED_Updates]
#CurrentHicn VARCHAR(500),
#DateReceived VARCHAR(20),
#FieldToBeChanged VARCHAR(500),
#CurrentFieldValue VARCHAR(500),
#NewFieldValue VARCHAR (500),
#RequestedBy VARCHAR(10),
#ID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
DECLARE #CurrentDBNote VARCHAR(MAX)
DECLARE #NewNote VARCHAR(MAX)
DECLARE #CountofHicn INT
SET #NEWNOTE = 'Isaac Pisors | ' + GetDate() + ' | '
+ 'Changing field: ' + #FieldToBeChanged + ' from ' + #CurrentFieldValue + ' to ' + #NewFieldValue
+ ', per ' + #RequestedBy + ' request. Also changing any related DOCS/FAXES records to correspond'
SET #CurrentDBNote=
(SELECT NOTES_GENERAL FROM PED_APPLICATIONS WHERE HICN_MEDICARE_NUMBER=#CurrentHicn AND (Cast(ISNULL(DATE_RECEIVED,'1900-01-01') as DATE)=CAST(#DateReceived AS DATE)))
--NOW ADD THE TWO:
SET #NewNote = #CurrentDBNote + CHAR(13) + #CurrentDBNote
--SEE IF THERE IS STILL A MATCHING RECORD
SET #CountofHicn=
(SELECT COUNT(*) FROM PED_APPLICATIONS WHERE HICN_MEDICARE_NUMBER=#CurrentHicn AND (CAST(ISNULL(DATE_RECEIVED,'1900-01-01') AS DATE)=CAST(#DateReceived AS DATE)))
IF #CountofHicn=0 --THERE IS NO LONGER A MATCHING RECORD - INSERT THAT NOTE AND CALL IT A DAY
BEGIN
UPDATE PED_PEDUPDATES SET COMPLETEDON=GetDate(), COMPLETEDBY='SSIS',
EXCEPTIONNOTE='Could not locate any records where HICN is ' + #CurrentHicn + ' and Date Received is ' + CAST(#DateReceived AS VARCHAR)
WHERE [ID]=#ID
END
ELSE --GO AHEAD AND DO THE UPDATE
BEGIN
UPDATE PED_APPLICATIONS SET #FieldToBeChanged = #NewFieldValue
WHERE HICN_MEDICARE_NUMBER=#CurrentHicn AND (CAST(ISNULL(DATE_RECEIVED,'1900-01-01') AS DATE)=CAST(#DateReceived AS DATE))
END
IF #FieldToBeChanged='HICN_MEDICARE_NUMBER' --THEN WE HAVE TO UPDATE DOCS TABLE, TOO
BEGIN
UPDATE PED_DOCS SET HICN_MEDICARE_NUMBER=#NewFieldValue
WHERE
(HICN_MEDICARE_NUMBER=#CurrentFieldValue AND (CAST(ISNULL(DATE_RECEIVED,'1900-01-01') AS DATE)=#DateReceived)) or
(HICN_MEDICARE_NUMBER=#CurrentFieldValue AND DATE_RECEIVED IS NULL)
END
IF #FieldToBeChanged='HICN_MEDICARE_NUMBER' --THEN OUR WHERE CLAUSE-HICN IS THE *NEW* HICN
BEGIN
UPDATE PED_APPLICATIONS SET NOTES_GENERAL=#NewNote
WHERE HICN_MEDICARE_NUMBER=#NewFieldValue AND (CAST(ISNULL(DATE_RECEIVED,'1900-01-01') AS DATE)=CAST(#DateReceived AS DATE))
END
ELSE --ELSE OUR WHERE CLAUSE-HICN IS THE *OLD* HICN
BEGIN
UPDATE PED_APPLICATIONS SET NOTES_GENERAL=#NewNote
WHERE HICN_MEDICARE_NUMBER=#CurrentHicn AND (CAST(ISNULL(DATE_RECEIVED,'1900-01-01') AS DATE)=CAST(#DateReceived AS DATE))
END
--FINALLY, UPDATE RECORD AS COMPLETE:
UPDATE PED_PEDUPDATES SET COMPLETEDON=GetDate(),COMPLETEDBY='SSIS' WHERE [ID]=#ID
END
GO

Short Term Fix
Instead of CAST(#DateReceived AS DATE), use CONVERT(date, #DateReceived, 112)
The value 112 is the style code for the yyyymmdd formated varchar you're using. See the cast and convert documentation for more details.
Also, you should verify that all values in the DATE_RECEIVED column of your table are in the correct format. Even one value that is not convertible will cause this error.
Proper Fix
#DateReceived should be passed in to the procedure as a date instead of a varchar.
The DATE_RECEIVED field in your table should be declared as a date instead of a varchar.
In general, avoid treating dates or times as strings in a database when there are native types for that purpose.

Related

i cant update to datetime table

i have already have date value
SET #LogDate1 = CAST(#logtanggal AS datetime)
SET #LogDate = CONVERT(varchar, #LogDate1, 20 )
#logtanggal is varchar, and i already convert it to datetime, the problem is when i try to update value of #logdate to the table, there are error mssg like
Msg 241, Level 16, State 1, Procedure LockAmountOnline_t24_Active, Line 108
Conversion failed when converting date and/or time from character string.
the table data type is already datetime, why i cant update to table?
the update query
SET #sql1 = 'UPDATE Lock_Amount_Trx
SET
GenerateDate = GETDATE(), -- datetime
LogDate ='''+#Logdate1+''', -- datetime
LogStatus = CASE WHEN tlat.logdescription = ''SUCCESS.UPD'' THEN ''SUCCESS''
WHEN tlat.logdescription = ''NOT.UPD-KTA'' THEN ''NOT CHANGED''
END ,
LogDescription = tlat.logdescription -- varchar
FROM ##TempLockAmmountTrx tlat, Lock_Amount_Trx lat
WHERE tlat.cuscode = lat.Custcode AND tlat.norekdeb = lat.NoRekDebet AND tlat.lockammount = lat.TotalLockAmount AND lat.Id ='''+ #idFile +''''
EXEC (#sql1)
converted varchar(top) and target table date format date (bottom)
There is literally no need for "dynamic" SQL here, there's nothing dynamic in your code. All you are doing here is creating a huge security flaw in your code. SQL injection is not a good thing, and you should never write code that can suffer from it.
Stop using dynamic SQL and the error doesn't happen:
UPDATE Lock_Amount_Trx
SET GenerateDate = GETDATE(), -- datetime
LogDate = #Logdate1, -- datetime
LogStatus = CASE WHEN tlat.logdescription = 'SUCCESS.UPD' THEN 'SUCCESS'
WHEN tlat.logdescription = 'NOT.UPD-KTA' THEN 'NOT CHANGED'
END,
LogDescription = tlat.logdescription -- varchar
FROM ##TempLockAmmountTrx tlat, Lock_Amount_Trx lat
WHERE tlat.cuscode = lat.Custcode
AND tlat.norekdeb = lat.NoRekDebet
AND tlat.lockammount = lat.TotalLockAmount
AND lat.Id = #idFile;
If you do ever need to actually use dynamic SQL, I suggest reading up on some of the basics, such as properly quoting your dynamic objects (which the above has none), and parametrising your statements. Rather than putting this all in the answer (which, considering that you don't need dynamic SQL, means it's not really really), you can read about this in my article Dos and Don'ts of Dynamic SQL.
Also, be very careful with your expression CONVERT(varchar, #LogDate1, 20 ). Always declare your length, scale and precissions when using data types.
You need to use parameterized Dynamic SQL :
SET #sql1 = 'UPDATE Lock_Amount_Trx
SET
GenerateDate = GETDATE(), -- datetime
LogDate = #LogDate1, -- datetime
LogStatus = CASE WHEN tlat.logdescription = ''SUCCESS.UPD'' THEN ''SUCCESS''
WHEN tlat.logdescription = ''NOT.UPD-KTA'' THEN ''NOT CHANGED''
END ,
LogDescription = tlat.logdescription -- varchar
FROM ##TempLockAmmountTrx tlat, Lock_Amount_Trx lat
WHERE tlat.cuscode = lat.Custcode AND tlat.norekdeb = lat.NoRekDebet AND tlat.lockammount = lat.TotalLockAmount AND lat.Id = #idFile'
exec sp_executesql #sql1, N'#LogDate1 DATETIME, #idFile varchar(255)', #LogDate1, #idFile
Note : I don't know what is the type of idfile so, change the type accordingly.
EDIT : As larnu pointed out that this query will not require any Dynamic SQL.
So, you can use plain update statement.

sql server concating or replacing, which one is better (faster)

I have to generate a very long procedure every time for a reporting system, so i created a template for my procedure and replacing the parts are needed to, but i could do it with Concat or +(&)
for example:
set #query = '... and (
--#InnerQueries
)'
set #query = replace(#query,'--#InnerQueries',#otherValues)
vs
set #query += ' and exists (...)'
if(#xxx is not null)
set #query += 'and not exists (...)'
with replace approach it's more readable and maintainable for me, but for sake of optimization, what about Concat and attaching string together?
with replace: there are a lot of searching but less string creation
and with concat: lot's of string creation but no searching
so any idea?
I assume you're talking about using CONCAT or REPLACE to build an SQL then run it. If ultimately you'll process fewer than 100 REPLACEments, I'd go with that approach rather than CONCAT because it's more readable.
If however, you're talking about using concat/replace to create report output data and you will e.g. be carrying out 100 REPLACE operations per row on a million rows, I'd do the CONCAT route
update 2:
there could be something missing here:
if i change first variable :#sourceText_Replace
to a max value of 8000 character, and continue to add to it:
set #sourceText_Replace += '8000 character length'
set #sourceText_Replace +=#sourceText_Replace
set #sourceText_Replace +=#sourceText_Replace
set #sourceText_Replace +=#sourceText_Replace
set #sourceText_Replace +=#sourceText_Replace
set #sourceText_Replace +=#sourceText_Replace
set #sourceText_Replace +=#sourceText_Replace
it works fine, even if go up until: 16384017 character length
so any idea here is as good as mine
orginal answer:
to summarize (and if i didnt make any mistakes):
if you are searching in a long text, dont even think about using replace, it took seconds not milliseconds, but for concat obviously does not make any difference
in the blew code, in first try(small text), i just used variables default values and did not append to them,
but for second try(long Text) , i just append result from previous loop run
for long text, i did not bothered to run the loop more than 20 time, because it took over minutes.
smallText: set #destSmallText_Replace =
longText: set #destSmallText_Replace +=
here is the code for test:
SET NOCOUNT ON
drop table if exists #tempReplace
drop table if exists #tempConcat
create table #tempReplace
(
[txt] nvarchar(max) not null
)
create table #tempConcat
(
[txt] nvarchar(max) not null
)
declare #sourceText_Replace nvarchar(max) = 'small1 text to replace #textToBeReplaced after param text'
declare #text_Replace nvarchar(max) = #sourceText_Replace
declare #textToSearch nvarchar(max) = '#textToBeReplaced'
declare #textToReplace nvarchar(max) = 'textToBeReplaced'
declare #concat_Start nvarchar(max) = 'small1 text to replace'
declare #concat_End nvarchar(max) = 'after param text'
declare #text_Concat nvarchar(max) = #concat_Start
declare #whileCounter int =0
declare #maxCounter int = 5
declare #startTime datetime = getdate();
declare #endTime datetime = getdate();
begin
set #startTime = getDate();
while(#whileCounter <=#maxCounter)
begin
--long text
set #text_Replace += replace(#sourceText_Replace,#textToSearch,#textToReplace + convert(nvarchar(10), #whileCounter)) + #textToSearch
--small text
--set #text_Replace = replace(#sourceText_Replace,#textToSearch,#textToReplace + convert(nvarchar(10), #whileCounter)) + #textToSearch
--print #destSmallText_Replace
insert into #tempReplace values(#text_Replace)
set #whileCounter+=1
end
set #endTime = getDate();
print 'passedTime ' + Convert(nvarchar(20), DATEPART(millisecond, #endTime) - DATEPART(millisecond, #startTime))
end
begin
set #whileCounter = 0;
set #startTime = getDate();
while(#whileCounter <=#maxCounter)
begin
set #text_Concat += concat(#concat_Start,#textToReplace + convert(nvarchar(10), #whileCounter),#concat_End) + #textToSearch
--print #sourceSmallText_Concat
insert into #tempConcat values(#text_Concat)
set #whileCounter+=1
end
set #endTime = getDate();
print 'passedTime ' + Convert(nvarchar(20), DATEPART(millisecond, #endTime) - DATEPART(millisecond, #startTime))
end

Issue with result set from stored procedure report generation

I have a Visual studio based stored procedure that generates a report for a monthly audit process. In the database being queried, all data for each month lives in its own individual table (Contacts_month_1, Contacts_month_2, etc.)
The SQL used in this report generation has some minor logic included, to allow it to work dynamically, rather than use hard coded dates. The problem arose at the start of January 2017, when I started receiving not just the results for the prior month, but additionally the prior year as well. To be specific, the audit report for December 2016 included data for both 12/2016 and 12/2015. Initially I thought it was a fluke of some kind based on the turn of the year, and we have not had this automated process during the turn as of yet. Unfortunately when I came in to the office today, inside the output file for January 2017, I also received the results for January 2016.
I attempted to include a year check to the process, however I am still getting the same result output. Any ideas would be appreciated.
Declare #GetMonth TinyInt
,#SessionTable varchar(50)
,#ContactTable varchar(50)
,#TableVersion varchar(2)
Declare #GetYear SmallInt
,#SessionTable_year varchar(50)
,#ContactTable_year varchar(50)
,#TableVersion_year varchar(4)
Set #GetMonth=MONTH(cast(GetDate() as Datetime))-1
Set #GetYear=YEAR(cast(GetDate() as Datetime))
If (#getmonth=0) Set #GetMonth=12 + (#GetYear-1)
Set #TableVersion=CAST(#getMonth as varchar(2))
Set #SessionTable='[CentralDWH].[dbo].[Sessions_month_' +#tableversion +']'
Set #ContactTable ='[CentralDWH].[dbo].[Contacts_month_' +#tableversion +']'
-- Select #GetMonth,#GetYear (DEBUGGING STATEMENT)
-- Select #SessionTable,#ContactTable (DEBUGGING STATEMENT)
Exec('SELECT [PBX_id] as AgentID
,[p22_value] as Skill
,''Athens'' as Location
,Convert(varchar(20),c.[local_start_time],120) as local_start_time
,convert(varchar(20),c.[local_end_time],120) as local_end_time
,U.[USER_NAME]
,call_id
FROM '+#SessionTable +' S
Inner join dbo.Users U on S.user_key=U.user_key
inner Join '+ #ContactTable+' C on S.contact_key=C.contact_key
Where is_screen > 0
And Unit_Num between 398003 and 398005
and P22_value is not null
and c.[local_start_time] > ' + #GetYear
+ ' order by local_start_time')
As I understand, the #GetMonth variable is used for returning the previous month
Set #GetMonth = MONTH(CAST(GetDate() AS Datetime)) - 1
After a quick look after you procedure my first issue was this line of code:
IF (#getmonth = 0)
SET #GetMonth = 12 + (#GetYear - 1)
I don't understand why are you setting the #GetMonth variable to 12 + current year -1 and I assume this is the cause to the problem.
Did you want to get the 12th month of the previous year when the current month is 1 (January)? If yes then you can easily change the If block to
If #GetMonth = 0
Begin
Set #GetMonth = 12
Set #GetYear = #GetYear - 1
End
Other issues:
It's recommended to keep the consistency of the names of the variables #GetMonth, #getmonth, this will cause an error if the database collation is case sensitive.
#GetMonth is declared as TinyInt and this will cause an arithmetic overflow if you try to store the year
I recommend testing the dynamic SQL statement that you are composing here with some hard coded values to check the results returned, you can use January and 2016 to check if the actual issue in your procedure or it's in your query.
Hope it helps
Thanks for your help, I figured out the root of the problem, and it was because i was not casting the GetYear as a varchar when trying to run the T-SQL statement. This in turn caused the variable to be completely ignored. I also cleaned up the query a little bit after realizing i was goofing up pretty hard.
Below is the cleaned up functional query, so that it may help someone in the future:
Declare #GetMonth SmallInt,
#SessionTable varchar(50),
#ContactTable varchar(50),
#TableVersion varchar(2),
#GetYear SmallInt,
#YearCheck varchar(4)
Set #GetMonth=MONTH(cast(GetDate() as Datetime))-1
Set #GetYear=YEAR(cast(GetDate() as Datetime))-1
If (#GetMonth=0)
Begin
Set #GetMonth =12
Set #GetYear =#GetYear - 1
End
Set #TableVersion=CAST(#GetMonth as varchar(2))
Set #SessionTable='[CentralDWH].[dbo].[Sessions_month_' +#tableversion +']'
Set #ContactTable ='[CentralDWH].[dbo].[Contacts_month_' +#tableversion +']'
Set #YearCheck=CAST(#GetYear as varchar(4))
--Select #GetMonth,#GetYear,#YearCheck (DEBUGGING STATEMENT)
-- Select #SessionTable,#ContactTable (DEBUGGING STATEMENT)
Exec('SELECT
[PBX_id] as AgentID,
[p22_value] as Skill,
''Athens'' as Location,
Convert(varchar(20),c.[local_start_time],120) as local_start_time,
convert(varchar(20),c.[local_end_time],120) as local_end_time,
U.[USER_NAME],
call_id
FROM '+#SessionTable +' S
Inner join dbo.Users U on S.user_key=U.user_key
inner Join '+ #ContactTable+' C on S.contact_key=C.contact_key
Where is_screen>0
And Unit_Num between 398003 and 398005
And P22_value is not null
And year(c.[local_start_time]) > '+#YearCheck+'
order by local_start_time')
Once I cleaned all this up and remembered to cast the year properly, everything fell into place.

In this stored procedure I'm getting error converting datatype varchar to datetime

Pls Help in this while I am executing this stored procedure I'm getting error
Error Converting datatype varchar to datetime
in the database that created as date only.
Columns contains date datatype
Lawcurdatefrm, Lawcurdateto
Lawcomdatefrom,Lawcomdateto
These four columns are of date datatypes
My requirement is I need a records FromDate to ToDate
Example
For current year I'm passing in those dates
Lawcurdatefrm = 01/04/2011
Lawcurdateto = 31/03/2012
For comparison of date I'm using
Lawcomdatefrom = 01/04/2010
Lawcomdateto = 31/03/2011
After applying this condition that should show records for current year and previous year. If no records found in the previous year that should display zero.
CREATE PROCEDURE MVR_New_L_New_La_RPRT_spO
#language Ctxt_Language,
#operationname Ctxt_Operation,
#ouinstance Ctxt_OuInstance,
#user Ctxt_User,
#Brndnamefrm Brndnamefrm,
#Brndnameto Brndnameto,
#Frgtypefrm Frgtypefrm,
#Frgtypeto Frgtypeto,
#LAWAND_SAL_ANANAME1 LAWAND_SAL_ANANAME1,
#LAWAND_SAL_PRINT LAWAND_SAL_PRINT,
#LAWAND_SAL_RENDERTYPE1 LAWAND_SAL_RENDERTYPE1,
#LAWAND_SAL_RPTID1 LAWAND_SAL_RPTID1,
#LAWAND_SAL_RPTYPE1 LAWAND_SAL_RPTYPE1,
#LAWAND_SAL_subaction LAWAND_SAL_subaction,
#Lawcomdatefrom Lawcomdatefrom,
#Lawcomdateto Lawcomdateto,
#Lawcurdatefrm Lawcurdatefrm,
#Lawcurdateto Lawcurdateto,
#LawCustCodefrm LawCustCodefrm,
#LawCustCodeto LawCustCodeto,
#LawDocnofrm LawDocnofrm,
#LawDocnoto LawDocnoto,
#Lawitemfrm Lawitemfrm,
#Lawitemto Lawitemto,
#lawprintcombo lawprintcombo,
#m_errorid m_errorid OUT
AS
Begin
--nocount should be switched on to prevent phantom rows
Set nocount on
--#m_errorid should be 0 to Indicate Success
Set #m_errorid=0
--declaration of local variables
--temporary and formal parameters mapping
SET #language = ltrim(rtrim(#language))
SET #operationname = ltrim(rtrim(#operationname))
SET #ouinstance = ltrim(rtrim(#ouinstance))
SET #user = ltrim(rtrim(#user))
SET #Brndnamefrm = ltrim(rtrim(#Brndnamefrm))
SET #Brndnameto = ltrim(rtrim(#Brndnameto))
SET #Frgtypefrm = ltrim(rtrim(#Frgtypefrm))
SET #Frgtypeto = ltrim(rtrim(#Frgtypeto))
SET #LAWAND_SAL_ANANAME1=ltrim(rtrim(#LAWAND_SAL_ANANAME1))
SET #LAWAND_SAL_PRINT=ltrim(rtrim(#LAWAND_SAL_PRINT))
SET #LAWAND_SAL_RENDERTYPE1=ltrim(rtrim(#LAWAND_SAL_RENDERTYPE1))
SET #LAWAND_SAL_RPTID1=ltrim(rtrim(#LAWAND_SAL_RPTID1))
SET #LAWAND_SAL_RPTYPE1=ltrim(rtrim(#LAWAND_SAL_RPTYPE1))
SET #LAWAND_SAL_subaction=ltrim(rtrim(#LAWAND_SAL_subaction))
SET #Lawcomdatefrom=ltrim(rtrim(#Lawcomdatefrom))
SET #Lawcomdateto=ltrim(rtrim(#Lawcomdateto))
SET #Lawcurdatefrm=ltrim(rtrim(#Lawcurdatefrm))
SET #Lawcurdateto=ltrim(rtrim(#Lawcurdateto))
SET #LawCustCodefrm=ltrim(rtrim(#LawCustCodefrm))
SET #LawCustCodeto=ltrim(rtrim(#LawCustCodeto))
SET #LawDocnofrm=ltrim(rtrim(#LawDocnofrm))
SET #LawDocnoto=ltrim(rtrim(#LawDocnoto))
SET #Lawitemfrm=ltrim(rtrim(#Lawitemfrm))
SET #Lawitemto=ltrim(rtrim(#Lawitemto))
SET #lawprintcombo=ltrim(rtrim(#lawprintcombo))
If #Lawcurdatefrm='' or isnull(#Lawcurdatefrm,'')=''
begin
raiserror('Please enter a valid Current From Date',16,1)
return
end
If #Lawcurdateto='' or isnull(#Lawcurdateto,'')=''
begin
raiserror('Please enter a valid Current to Date',16,1)
return
end
--select 'albus',#Lawcomdatefrom,#Lawcomdateto,#Lawcurdatefrm,#Lawcurdateto
(SELECT isnull (Itemqty1,0) from law_sale_view where custordinv_hdr_tran_date between #Lawcomdatefrom and #Lawcomdateto )
(SELECT isnull(itemvalue1,0) from law_sale_view where custordinv_hdr_tran_date between #Lawcurdatefrm and #Lawcurdateto)
Select 0 'Lw_BrndNm',
convert(varchar(10),custordinv_hdr_anchor_date,109) 'Lw_Comfrmdate',
itemqty1 'Lw_ComQt',
convert(varchar(10),custordinv_hdr_anchor_date,109) 'Lw_Comtodate',
itemvalue1 'Lw_ComVal',
convert(varchar(10),custordinv_hdr_tran_date,109) 'Lw_Curfrmdate',
custordinv_dtl_item_qty'Lw_CurQt',
convert(varchar(10),custordinv_hdr_tran_date,109) 'Lw_Curtodate',
custordinv_dtl_item_amt 'Lw_Curval',
custlo_cust_code 'Lw_CustCod',
custlo_cust_name 'Lw_CustNam',
stdattrvalue1 'Lw_Frghttyp',
custordinv_dtl_item_tcd_code 'Lw_ItmCod',
itemdesc 'Lw_ItmDes',
custordinv_dtl_uom 'Lw_UOM'
from law_sale_view
--where custlo_cust_code=custlo_cust_code
Set nocount off
End
Please remove
convert(varchar(10),custordinv_hdr_anchor_date,109)
in all datetime place & try...
Rewrite the date value to something like yyyy/MM/dd format, for example your "31/03/2011" to "2011/03/31". Why? when your transform string "31/03/2011" to date the 31 will be assumed to be month instead of day.

Trouble creating error message in SQL Server

I have the following piece of code within my stored procedure, I know it doesn't work and should not work but I wanted to illustrate my intentions:
declare #ErrorMessages varchar;
set #ErrorMessages = 'An existing deposit on this property ends after the intended start date for the new deposit. ' +
'Existing End Date: ' + #PreviousDepositEndDate + '. Intended Start Date: ' + #TenancyAgreementStartDate
raiserror 50002 #ErrorMessages
Can anyone tell me what I should be doing? Or any links on creating this type of string.
EDIT: Forgot to say that the #Dates are both of datetime, the error message is that it cannot be converted from datetime to string
Try this:
declare #ErrorMessages varchar(255);
Using just #ErrorMessages varchar; gives you a varchar(1).
set #ErrorMessages =
'An existing deposit on this property ends after the intended start date for the new deposit. ' +
'Existing End Date: ' +
#PreviousDepositEndDate + '. Intended Start Date: ' + #TenancyAgreementStartDate
raiserror(#ErrorMessages, 16, 1)
If you wan't to specify the error number, you must first use sp_addmessage and define the error message, which you can reference in raiserror. You may have to insert some casts, depending on what types #PreviousDepositEndDate and #TenancyAgreementStartDate are.
Here's a slightly different version which some people like because it emulates C printf style:
-- Test data
declare #PreviousDepositEndDate varchar(30) = cast(getdate() - 1 as varchar(30))
, #TenancyAgreementStartDate varchar(30) = cast(getdate() as varchar(30))
-- Throw
raiserror (N'An existing deposit on this property ends after the intended start date for the new deposit. Existing End Date: %s. Intended Start Date: %s',
16, -- Severity,
1, -- State,
#PreviousDepositEndDate, -- First argument.
#TenancyAgreementStartDate) -- Second argument.
More info can be found in this MSDN link: http://msdn.microsoft.com/en-us/library/ms178592.aspx