I am trying to set a value for a 2 parameters in SQL:
#DateLoading
#DateLoading2
I declare them as datetime:
DECLARE #DateLoading AS datetime
DELCARE #DateLoading2 AS datetime
In the WHERE clause I set the parameters as following:
WHERE
o.DateLoading >= #Datetoloading AND
o.DateLoading < #Datetoloading2 AND
I have problem setting the scalar value. I've tried with this code, but the error is the same:
SET #DateLoading = COALESCE(CASE WHEN #DateLoading = 'Current Month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) ELSE NULL END,
CASE WHEN #DateLoading = 'Previous Month' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0) ELSE NULL END,
CASE WHEN #DateLoading = 'Previous 7 Days' THEN DATEADD(HOUR, 6, DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) - 1, 0)) ELSE NULL END,
DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
);
SET #DateLoading2 = COALESCE(
CASE WHEN #DateLoading2= 'Current Month' THEN DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0) ELSE NULL END,
CASE WHEN #DateLoading2= 'Previous Month' THEN DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0) ELSE NULL END,
CASE WHEN #DateLoading2= 'Previous 7 Days' THEN DATEADD(HOUR,6,DATEADD(DAY,DATEDIFF(DAY,0,GETDATE()),0)) ELSE NULL END,
GETDATE()
)
Here is the error messages:
Msg 137, Level 15, State 2, Line 6
Must declare the scalar variable "#TimePeriod".
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near 'E'
Yes, you were right. I got rid of [S, [E]... (I wanted them to be alias) but I got rid of them... Also, the second mistake was #TimePeriod... I changed it to #DateLoading... But now, there is only 1 error message:
Conversion failed when converting data and/or time from character string
The client should enter Start Date and End Date so as to receive results. But the code I have for setting the scalar value for these two parameters is totally wrong.
Related
I am trying to find the difference between two dates in SQL but ignoring weekends...
I've tried looking at other answers and keep getting the error:
Msg 4104, Level 16, State 1, Line 7
The multi-part identifier "ste.TransactionDate" could not be bound.
My current code is:
DATEDIFF(WEEKDAY, ste.TransactionDate, ste.SettlementDate) AS DaysToCSD,
and I did change this to
DECLARE #d1 datetime, #d2 datetime
SELECT #d1 = ste.TransactionDate, #d2 = ste.SettlementDate
SELECT DATEDIFF(dd, #d1, #d2) - (DATEDIFF(wk, #d1, #d2) * 2) -
CASE WHEN DATEPART(dw, #d1) = 1 THEN 1 ELSE 0 END +
CASE WHEN DATEPART(dw, #d2) = 1 THEN 1 ELSE 0 END
I am not great at SQL..not a dev...so any help appreciated!
SO! I've a tricky set of data I'm working with and I've got it down to what I hope is the last part.
The goal is to return records from a 24 hour period. Column notes is varchar and contains the date I need to check against. I've truncated the datetime portion Notes and converted it to ISO8601 but I cannot seem to get it to check against >= DATEADD(day, -1, GETDATE())
Column data sample: Record updated: 04/06/2009 12:00:00 AM
My initial query attempt:
SELECT OrderNumber,
SUBSTRING(notes, 15, 35) as notes_truncated, //verify we got the complete date/time for conversion
CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) AS convertTo_ISO8601 // convert it to recognizable datetime
FROM table
WHERE CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) >= DATEADD(day, -1, GETDATE()) // substring -> convert -> compare against today's date and return those from within 24 hours
AND notes IS NOT NULL // necessary parameter
AND notes LIKE '%returnMe%'; // necessary parameter
errors: Conversion failed when converting date and/or time from character string
DECLARE #sillyString datetime;
SET #sillyString = CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126);
SELECT SUBSTRING(notes, 15, 35) as notes_truncated,
CONVERT(nvarchar(30), SUBSTRING(notes, 15, 35), 126) AS UsingConvertTo_ISO8601
FROM table
WHERE #sillyString >= DATEADD(day, -1, GETDATE())
AND notes IS NOT NULL
AND notes LIKE '%returnMe%';
error: Invalid column name 'notes'
DECLARE #value varchar(20);
DECLARE #sqlText nvarchar(1000);
DECLARE #sillyString datetime;
SET #value = 'notes'
SET #sillyString = CONVERT(nvarchar(30), SUBSTRING(#value, 15, 35), 126);
SELECT SUBSTRING(notes, 15, 35) as notes_truncated,
#sillyString AS UsingConvertTo_ISO8601
FROM table
WHERE notes IS NOT NULL
AND notes LIKE '%returnMe%';
errors: UsingConvertTo_ISO8601 returns with a value of 1900-01-01 00:00:00.000 so then doing modifying the WHERE to WHERE #sillyString >= DATEADD(day, -1, GETDATE()) AND notes IS NOT NULL AND notes LIKE '%returnMe%' returns 0 records.
Your assistance is much appreciated!
Try a quick check to see if the string is not a date for any records you will be returning:
SET DATEFORMAT ymd -- make sure the date part is in the same order as 126 (4) ISO8601
SELECT OrderNumber,
SUBSTRING(notes, 15, 35) as notes_truncated
FROM table
WHERE ISDATE(SUBSTRING(notes, 15, 35)) = 0
AND notes IS NOT NULL // necessary parameter
AND notes LIKE '%returnMe%'; // necessary parameter
I want to view the session hours of previous 3 months in my SQL (hrs column is declared as nvarchar), I need to convert the data into float if I want to view the data of last 3 months but I am getting some errors
SELECT sum(convert(float, hrs))
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
SELECT sum(cast(hrs as float))
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to float.
SELECT CAST(CAST (hrs AS NUMERIC(19,4)) AS INT)
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 8114, Level 16, State 5, Line 1
Error converting data type nvarchar to numeric.
SELECT CAST(CAST (hrs AS int) AS INT)
FROM companysonvinunitvenue
WHERE date >= DATEADD(day, -90, GETDATE())
Error:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '02:00:00 ' to data type int.
I tried these four ways and failed in all of them, how I need to do this?
First, use date and time data types for datetime values. And you will avoid these and many other troubles and also save disk space, RAM, reduce number of reads and so on.
As for your problem. For Sql Server 2008+
DECLARE #companysonvinunitvenue TABLE (hrs NVARCHAR(10))
INSERT #companysonvinunitvenue VALUES ('02:00:00'),('21:31:03')
SELECT DATEPART(HOUR,CAST(hrs AS time))
FROM #companysonvinunitvenue
For other versions
DECLARE #companysonvinunitvenue TABLE (hrs NVARCHAR(10))
INSERT #companysonvinunitvenue VALUES ('02:00:00'),('21:31:03')
SELECT cast(LEFT(hrs,2) AS INT)
FROM #companysonvinunitvenue
I'm making a query (and a long, nasty bugger it is) to return dynamically updating values from an SAP system. I've got everything figured out but how to make the column headers what I want. They need to be the name of the previous 11 months and this month (or the 3 letter abbreviation).
Currently, I just have
SELECT ... AS [OCT]
for this month, but in two days it's going to be different, and I'd like to have the query auto-update the column headers each time it is run.
I figured out that I can use the variables I have declared to use in my functions to get the name three letter name of the month:
DECLARE #last_month DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 0, 0)
SELECT CONVERT(char(3), #last_month);
to return the selected month. How do I get this to be usable in the "AS" field?
Here is what I currently have:
DECLARE #last_two_months DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)
DECLARE #last_month DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 0, 0)
SELECT (a whole mess of things that somehow work) AS [SEPT],
Table.CurrentTotal AS [OCT];
I'd like to replace [OCT] with something that will return OCT as the column header for the next two days and then return NOV for the next month, and similarly changing [SEPT] to something that will return SEP for the next two days, then return OCT for the next month.
Use Dynamic Query
DECLARE #last_month DATE = DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 0, 0),
#alias char(3),
#sql nvarchar(max)=''
SELECT #alias= CONVERT(char(3), #last_month);
set #sql = 'SELECT ... as ['+#alias+']..'
--Print #sql
exec sp_executesql #sql
Use the Print Statement to debug the dynamic query
I am getting the following error from this piece of code
Msg 242, Level 16, State 3, Line 3
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
T-SQL:
datediff(dd, a.ContractStartDate,
cast(case when isdate(
cast(datepart(month, dateadd(mm, 0, a.WarrStartDate)) as varchar(2)) + '/' +
cast('00' + datepart(DAY, a.WarrStartDate) as varchar(2)) + '/' +
cast(datepart(year, dateadd(YEAR, case when a.TRSCustNO = 89555 then 2 else 3 end, a.WarrStartDate)) as varchar(4)))=0
then
cast('00'+datepart(month,dateadd(mm,0,a.WarrStartDate))as varchar(2))+'/'+
cast('00'+datepart(DAY,dateadd(dd,-1,a.WarrStartDate)) as varchar(2)) +'/'+
cast(datepart(year,dateadd(YEAR,case when a.TRSCustNO = 89555 then 2 else 3 end
,a.WarrStartDate))as varchar(4))
else
cast('00'+datepart(month,dateadd(mm,0,a.WarrStartDate))as varchar(2))+'/'+
cast('00'+datepart(DAY,a.WarrStartDate) as varchar(2)) +'/'+
cast(datepart(year,dateadd(YEAR,case when a.TRSCustNO = 89555 then 2 else 3 end
,a.WarrStartDate))as varchar(4)
) end
as datetime)
) as EarnDays
unless I am missing something, this can all be simplified like this. I didn't see a reason to be casting between date and varchar types.
case
when datediff(dd,a.ContractStartDate,
dateadd(year,(case when a.TRSCustNO = 89555 then 2 else 3 end), a.WarrStartDate)
)=0
then
dateadd(year, (case when a.TRSCustNO = 89555 then 2 else 3 end),
dateadd(dd,-1,a.WarrStartDate)
)
else
dateadd(year, (case when a.TRSCustNO = 89555 then 2 else 3 end), a.WarrStartDate)
end as EarnDays
Let me know if I missed the point of it.
If you want to know why you were getting the error, just don't cast it back to a date and look at the output.