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.
Related
To get the required table I have to input the value "201801" into the stored procedure query. I want to place the following code:
SELECT CONVERT(nvarchar(6), GETDATE(), 112)
In the following Sp:
USE [MDAmanager]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[sqSupplierBalances]
#Period = 201801,
#SupplierString = 'select SupplierID from Suppliers ',
#SelectionString = 'select * from vSupplierBalances order by
ControlOfficeName, PortfolioName, OwnerEntityName, RegionName,
PropertyName, PropertyManagerName, Custom1Name, Custom2Name,
ServiceTypeDescription, AnalysisCode, SupplierName',
#WithCommitments = NULL,
#UserID = NULL,
#ExcludeInDispute = NULL,
#IncludeSupplierPropertyReference = NULL
SELECT 'Return Value' = #return_value
GO
Is it possible to assign a value to the first code example and replace the "201801" in the second code example with that variable. I have been trying this but not getting it right.
Update: So I realize M query functions and SQL server functions are different. I don't how to go about answering my own question but I figured I'd give the answer here anyway.
I replaced the initial date code with:
Perdiod0 = (Date.Year(DateTime.LocalNow()) * 100) +
Date.Month(DateTime.LocalNow())
And then just replaced the 201801 with:
'" & Text.From(Period0) & "'
Seems to work now
I'm trying to compare if my variable datetime is NULL, but it doesn't work, I'm new making comparising in SQL, so could someone said me how is the good way. This is my code:
declare #FechaInicial datetime
set #FechaInicial = (select FecharIncialDescarga
from Contenedores where Id_Contenedor=#IdContenedor)
if(#FechaInicial = NULL) ---
begin
end
The direct answer to your question is is null:
if (#FechaInicial IS NULL)
This is because almost any comparison to NULL returns NULL, and NULL is treated as false.
However, I want to point out that you might really intend this logic:
if (not exists (select 1 from Contenedores where Id_Contenedor = #IdContenedor))
begin
. . .
end;
Although there is nothing wrong with assigning the value to a variable and checking for NULL, this is clearer and can be more efficient.
You can try this with if(#FechaInicial IS NULL) as below.
declare #FechaInicial datetime
set #FechaInicial = (select FecharIncialDescarga from Contenedores
where Id_Contenedor=#IdContenedor)
if(#FechaInicial IS NULL) ---
begin
end
If you want to check NULL and also empty, you can try if(ISNULL(#FechaInicial, '') = '') as below.
declare #FechaInicial datetime
set #FechaInicial = (select FecharIncialDescarga
from Contenedores where Id_Contenedor=#IdContenedor)
if(ISNULL(#FechaInicial, '') = '') ---
begin
end
Also a recommendation, Instead of a SET used above, you can refactor it as below with a SELECT
SELECT #FechaInicial = FecharIncialDescarga
FROM Contenedores WHERE Id_Contenedor = #IdContenedor
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.
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.
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.