DECLARE #FINANCIALYEAR AS varchar(30)
DECLARE #FINALFINANCIALYEAR AS int
SELECT #FINANCIALYEAR=CONVERT(VARCHAR,YEAR(GETDATE())-2) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE())-1) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE()))
set #FINALFINANCIALYEAR = CONVERT(int,#FINANCIALYEAR)
print #FINALFINANCIALYEAR
i want final output in int format so iam doing above code but it gives me error plz help
Simple query
SELECT CONVERT(VARCHAR,YEAR(GETDATE())-2) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE())-1) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE()))
Select YEAR (GetDate())-2,YEAR (GetDate())-1, YEAR (GetDate())
Just check what your variable is after your SELECT:
DECLARE #FINANCIALYEAR AS varchar(30)
DECLARE #FINALFINANCIALYEAR AS int
SELECT #FINANCIALYEAR=CONVERT(VARCHAR,YEAR(GETDATE())-2) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE())-1) + ', ' +
CONVERT(VARCHAR,YEAR(GETDATE()))
SELECT #FINANCIALYEAR
The output is:
2008, 2009, 2010
This is clearly NOT a valid INT value - so it's obvious you're getting a conversion error.....
SELECT DATEPART(YEAR, GETDATE()), DATEPART(YEAR, GETDATE()) - 1, DATEPART(YEAR, GETDATE()) - 2
this year is
Select datepart(year,getdate())
or
year(getdate())
Related
I am having an issue converting below to a DateTime, I am only able to get the date portion of the string. My goal is to get both the date & time.
declare #col varchar(14) = '20220602235900';
select CONVERT(datetime, CAST(#col AS varchar(8)), 121) dtimecre
Steps:
Read the documentation for CONVERT and pick the closest format to use
Do some string manipulation to get the desired format
Convert.
DECLARE #col varchar(14) = '20220602235900';
SELECT
CONVERT(date, SUBSTRING(#col,1,8), 121) [Date Component]
, CONVERT(time, SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 8) [Time Component]
, CONVERT(datetime, SUBSTRING(#col,1,4) + '-' + SUBSTRING(#col,5,2) + '-' + SUBSTRING(#col,7,2) + ' ' + SUBSTRING(#col,9,2) + ':' + SUBSTRING(#col,11,2) + ':' + SUBSTRING(#col,13,2), 120) [DateTime Representation];
Returns:
Date Component
Time Component
DateTime Representation
2022-06-02
23:59:00.0000000
2022-06-02 23:59:00.000
And another variant with a smaller amount of SUBSTRING:
DECLARE #col varchar(14) = '20220602235900';
SELECT DateComponent = CAST(DatePartString AS DATE),
TimeComponent = CAST(TimePartString AS TIME),
DateAndTime = CAST(DatePartString + ' ' + TimePartString AS DATETIME)
FROM (VALUES(#col)) AS O (DateColumn)
CROSS APPLY (
SELECT DatePartString = LEFT(DateColumn, 8),
TimePartString = FORMAT(CAST(SUBSTRING(DateColumn, 9, 6) AS INT), '##:##:##')
) AS String;
I am trying to write this using SQL SERVER:
"Hi! Today is ... This is the day number... of the year. New year's eve is in ... days".
My code runs with no problem but I can't print as well. What am I doing wrong? I haven't finished the whole phrase because I need to fix the problem before I get to the last part.
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
-- SELECT Numbertoday = DATEDIFF(day,STR(YEAR(#dayofyear),4)+'0101',#dayofyear)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + of the year.')
Another way to do is:
declare #today varchar(11) = convert(varchar(11), getdate(), 1);
declare #dayOfTheYear int = datepart(DAYOFYEAR, getdate());
declare #untilNewYearsEve int = datepart(dayofyear, datefromparts(year(getdate()), 12, 31)) - #dayOfTheYear
-- if you use print, you should see the result under the 'messages' tab not in the 'results' tab in SSMS
print 'Hi! Today is '+ #today + '. ' + 'This is the day number '+ cast( #dayOfTheYear as varchar(3)) + '. New year''s eve is in '+
cast (#untilNewYearsEve as varchar(3)) + ' days.'
This should work perfectly fine.
while seeting the day of year you need to put #current date so it will work because you are trying to get a day from a #currentdate
DECLARE
#currentDate DateTime
SET #currentDate = GETDATE();
DECLARE #dayofyear datetime
SET #dayofyear=DATEDIFF(day,STR(YEAR(#currentDate),4)+'0101',#currentDate)+1
print('Hi! Today is '+ CONVERT(VARCHAR(10), #currentDate , 111) + '. ' + 'This is the day number '+ ' ' + CONVERT (VARCHAR(10), #dayofyear) + 'of the year.')
Just for fun, you can use concat()
Example
Print concat('Hi! Today is '
,format(GetDate(),'dddd, MMM d, yyyy.')
,' This is the day number '
,DateDiff(DAY,datename(YEAR,getdate())+'0101',getdate()) + 1
,' of the year.'
)
Results
Hi! Today is Thursday, Jul 4, 2019. This is the day number 185 of the year.
You can simplify things a bit using DAYOFYEAR parameter in the DATEPART function if using SQL 2008 and above. And you don't really need to declare a variable for the date.
Sample Code:
print('Hi! Today is '+ convert(varchar(10), getdate() , 111) + '. ' + 'This is the day number' + ' ' + convert(varchar, datepart(dayofyear, getdate()))) + ' of the year.'
Results:
Hi! Today is 2019/07/05. This is the day number 186 of the year.
Im filling a table and I need this table get the daily sells, but summing and counting, sells and clients by day respectively.
But is not grouping the sales by day this is the QUERY:
insert into VentaDiariaTienda(
Fecha,
VentaDia,
Tda_Codigo,
NumeroClientes,
PromedioVtaCliente,
EditName,
EditDateTime)
select
DATENAME(dw, T_Fecha) + ', ' +
cast(datepart(dd, T_Fecha) as char(2)) + ' ' +
datename(mm, T_Fecha) + ' ' +
cast(datepart(yyyy,T_Fecha) as char(4)),
sum(T_ImporteTotal/1.16),
[FolTda_Codigo],
count(T_Cliente),
sum(T_ImporteTotal/1.16)/count(T_Cliente),
'Admin',
GETDATE()
from #Tickets
group by T_Fecha,[FolTda_Codigo]
and this is the out of this query
Thanks for your replys.
You will have to "round down" the T_Fecha values to a day, so you might try to insert the following records:
SELECT
DATENAME(dw, dt) + ', ' +
DATENAME(dd, dt) + ' ' +
DATENAME(mm, dt) + ' ' +
DATENAME(yy, dt),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente),
'Admin',
GETDATE()
FROM #Tickets
CROSS APPLY (
VALUES (DATEADD(day, DATEDIFF(day, 0, T_Fecha), 0))
) d (dt)
GROUP BY dt, FolTda_Codigo
My proposition:
You can use format function (since SQL Server 2012, else use Wolfgang Method)
Be carefull with divide by "Count" function. If you result is 0 (by example if T_Client is always null) you will have an error
Not necessary to use "outer apply" instruction in this case, group on by date and not by date and time
Something like this:
SELECT
FORMAT(T_Fecha, 'dddd, dd MMMM yyyy', 'en-US' ),
SUM(T_ImporteTotal)/1.16,
FolTda_Codigo,
COUNT(T_Cliente),
case when COUNT(T_Cliente)=0 then null else SUM(T_ImporteTotal)/1.16/COUNT(T_Cliente) end,
'Admin',
GETDATE()
FROM #Tickets
GROUP BY cast(T_Fecha as date), FolTda_Codigo
For SQL Server 2008, replace format by
DATENAME(dw, T_Fecha) + ', ' + DATENAME(dd, T_Fecha) + ' ' +
DATENAME(mm, T_Fecha) + ' ' + DATENAME(yy, T_Fecha),
Using SQL Server 2005
Date Time
20060701 090000
20060702 020000
20060703 180000
...
Date and Time datatype is varchar
Tried Query
select Convert(datetime, Convert(char(10), date, 103) + ' ' + Convert(char(8), time, 108), 103) from table
SELECT
CAST(
DATEADD(dd, 0, DATEDIFF(dd, 0, date)) + ' ' +
DATEADD(Day, -DATEDIFF(Day, 0, time), time)
as datetime) from table
It showing error as out of range value.
How to solve this issue.
Need Sql Query Help
First off, why are you storing a DATETIME in a VARCHAR?
This should be able to help
DECLARE #Table TABLE(
Val VARCHAR(20)
)
INSERT INTO #Table (Val) SELECT '20060701 090102'
INSERT INTO #Table (Val) SELECT '20060702 020000'
INSERT INTO #Table (Val) SELECT '20060703 180000'
SELECT *,
CAST(SUBSTRING(Val,1,8) + ' ' + SUBSTRING(Val,10,2) + ':' + SUBSTRING(Val,12,2) + ':' + SUBSTRING(Val,14,2) AS DATETIME)
FROM #Table
I came across a similar issue a few years ago, when importing HL7 messages. Here is a copy of the function I used. It creates a DateTime string with the time component correctly separated into hh:mm:ss, which is needed for the cast to DateTime.
CREATE FUNCTION fn_StringDateTietoDateTime
(
#Date varchar(15)
)
RETURNS datetime
AS
BEGIN
DECLARE #Result DATETIME
SET #Result = NULL
If len(#Date) > 0
BEGIN
SELECT #Result = CAST(SUBSTRING(#hl7date, 1, 8) + ' ' + SUBSTRING(#hl7date, 10, 2) + ':' +
SUBSTRING(#date, 12, 2) + ':' + SUBSTRING(#date,14, 2) AS DATETIME)
END
RETURN #RESULT
END
How to convert the datetime value to nvarchar and want to format it "Month, Year" e-g October 1st 2009 value should get converted to "October, 2009"
use this:
select CONVERT(nvarchar(50), DATENAME(m, getdate())
+ ', '
+ DATENAME(yyyy, getdate())
)
OUTPUT:
--------------------------------------------------
October, 2009
(1 row(s) affected)
Try this
DECLARE #DateTime DATETIME
SET #DateTime = '01 Oct 2009'
SELECT #DateTime
SELECT DATENAME(mm, #DateTime) + ', ' + CAST(DATEPART(yy, #DateTime) AS VARCHAR(4))
One way would be to use datename to extract the pieces you needed in name format, so:
select Convert(nvarchar,datename(m,getdate())) + N', ' + Convert(nvarchar,datename
(yy,getdate()))
And replace getdate() with your date variable / field.
The DateName function will provide the formatting you require:
DATENAME(m, date) + ', ' + DATENAME(yyyy, date)
Converting to nvarchar of a specific size can be done through the cast function:
CAST(value AS nvarchar[30])
Try the following query:
Select case Convert(int, day(getdate())) when 1 then '1st' when 2 then '2nd'
when 3 then '3rd' else Convert(varchar, day(getdate()))+'th' end +' '+ Convert(varchar, Datename(m,getdate()))+' ' +Convert(varchar, Datename(yy,getdate())) as Date
You can replace getdate() with any other date.
Please check if it helps.