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.
Related
So, I need to show the consumption of the material on the current month and the last 6 too. I'm trying to put an alias name on the columns with the respective month just like "MM/YY".
Example of the columns: 08/17 | 07/17 | 06/17 | ... | 02/17
DECLARE #mes_atual DATE; SET #mes_atual = CAST(FORMAT(GETDATE(),'MM/YY') AS DATE)
DECLARE #mes1 DATE; SET #mes1 = DATEADD(MM, -1, #mes_atual); SET #mes1 = CAST(#mes1 AS VARCHAR)
DECLARE #mes2 DATE; SET #mes2 = DATEADD(MM, -2, #mes_atual); SET #mes2 = CAST(#mes2 AS VARCHAR)
DECLARE #mes3 DATE; SET #mes3 = DATEADD(MM, -3, #mes_atual); SET #mes3 = CAST(#mes3 AS VARCHAR)
DECLARE #mes4 DATE; SET #mes4 = DATEADD(MM, -4, #mes_atual); SET #mes4 = CAST(#mes4 AS VARCHAR)
DECLARE #mes5 DATE; SET #mes5 = DATEADD(MM, -5, #mes_atual); SET #mes5 = CAST(#mes5 AS VARCHAR)
DECLARE #mes6 DATE; SET #mes6 = DATEADD(MM, -6, #mes_atual); SET #mes6 = CAST(#mes6 AS VARCHAR)
SET #mes_atual = CAST(#mes_atual AS VARCHAR)
DECLARE #query VARCHAR;
DECLARE #selects VARCHAR;
SET #selects = 'QT_CONS_MES_ATUAL AS [' + CAST(#mes_atual AS VARCHAR) + '], QT_CONS_MES_1 AS [' + CAST(#mes1 AS VARCHAR) + '], QT_CONS_MES_2 AS [' + CAST(#mes2 AS VARCHAR) + '], QT_CONS_MES_3 AS [' + CAST(#mes3 AS VARCHAR) + '], QT_CONS_MES_4 AS [' + CAST(#mes4 AS VARCHAR) + '], QT_CONS_MES_5 AS [' + CAST(#mes5 AS VARCHAR) + '], QT_CONS_MES_6 AS [' + CAST(#mes6 AS VARCHAR) + ']'
SET #query = 'SELECT [VERSAO]
,[IN_TP_DISP]
,[CD_OWNER]
,[DS_OWNER]
,[OP_ITEM_PROD]
,[DS_PRODUTO]
,[CD_MAT_GRUPO]
,[CD_MAT_SUBGRUPO]
,[CD_MAT_CLASSE]
,[CD_MAT_NIVEL4]
,[CD_MAT_NIVEL5]
,[CD_UNMED_EST]
,[CD_DIVISAO]
,[IN_CTR_DISP]
,[IN_TIPO_REPOS]
,[QT_ETQ_MAXIMO]
,[QT_ETQ_MINIMO]
,[QT_LOTE_COMPRA]
,[QT_SALDO_ATUAL]
,[VL_SALDO_ATUAL]
,[QT_SALDO_RES]
,[QT_SALDO_ENC]
,[QT_SALDO_DISP]
,'+#selects+'
,[SQ_MOVTO]
,[QT_SALDO_CUR]
,[QT_SALDO_BENTO]
,[QT_SALDO_BAURU]
,[CD_FOR_ITEM]
,[VL_CUSTO_ULT_COMPRA]
,[CD_PESSOA_FORN]
,[NOME_FORN]
,[AN_NFE]
,[DT_ENTRADA]
,[AN_PC]
FROM [dbo].[VW_SQL_CONSUMO_BI]'
EXEC(#query)
I'm trying to put the alias name of some columns with a dinamic date but when I convert the date to a VARCHAR data, build the query and exec it i get the error:
Mensagem 241, NĂvel 16, Estado 1, Linha 3
Conversion failed when converting date and/or time from character string.
Ps: The error message is in portuguese but I hope u guys can help me.
The problem is your variable at the very top. How can a month and year be a date? You need a day. Get rid of that silly cast/format stuff and just set your date to getdate.
DECLARE #mes_atual DATE; SET #mes_atual = GETDATE()
select #mes_atual
you cannot create a valid date without a day
So put GetDate in your variable and use Format to only show the year and month
DECLARE #mes_atual DATE
SET #mes_atual = GetDate()
select #mes_atual as mes_atual,
FORMAT(#mes_atual,'MM/yy') AS date
this returns
mes_atual date
2017-08-04 08/17
Don't Cast as Date. Just use the formatting to get what you want.
Notice the yy is lowercase
Select FORMAT(#mes_atual,'MM/yy')
DECLARE #mes_atual DATE; SET #mes_atual = GETDATE()
Select #mes_atual
Select FORMAT(#mes_atual,'MM/yy')
Will render
2017-08-04
08/17
I have used below code to convert a datetime to string,
DECLARE #StartDate datetime = '08/07/2015 12:10 AM'
set #StartDate = dateadd(hour,12, #StartDate);
select CONVERT(VARCHAR(10),#StartDate, 101) + RIGHT(STUFF(CONVERT(VARCHAR(32), #StartDate,100), 18, 0, ' '),8)
but I am getting output as "08/07/201512:10 PM" , there is no space between date and time, How can I correct this?
If i correctly understood your problem then there is small correction required in your code. I added +' '+ i.e. a blank space between your date convert and right stuff. Complete code is as given below.
DECLARE #StartDate DATETIME = '08/07/2015 12:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8)
Result
08/07/2015 12:10 PM
i.e. space between date and time also space between 12:10 and PM
To cover new case provided :
DECLARE #StartDate DATETIME = '08/07/2015 2:10 AM'
SET #StartDate = DATEADD(HOUR,12, #StartDate);
SELECT CONVERT(VARCHAR(10),#StartDate, 101) +' '+
LTRIM(RIGHT(STUFF(CONVERT(VARCHAR(32),#StartDate,100), 18, 0, ' '),8))
Result
08/07/2015 2:10 PM
i.e. no extra space when time is like 2:10 PM
Here is one way to do it:
DECLARE #StartDate datetime = '2015-08-07T00:10:00';
SET #StartDate = dateadd(hour,12, #StartDate);
SELECT #StartDate As StartDate,
CONVERT(CHAR(10), #StartDate, 101) + ' ' + -- DateString,
SUBSTRING(CONVERT(CHAR(19), #StartDate, 100), 13, 5) + ' ' + -- TimeString
RIGHT(CONVERT(CHAR(19), #StartDate, 100), 2) As DateString -- AM/PM
Result:
StartDate DateString
----------------------- -------------------
2015-08-07 12:10:00.000 08/07/2015 12:10 PM
The following snippet will produce the output you've indicated in the question.
SET DATEFORMAT MDY;
DECLARE #StartDate DATETIME = '08-07-2015 12:10 AM';
SET #StartDate = DATEADD(HOUR, 12, #StartDate);
SELECT CONVERT(VARCHAR, #StartDate, 103) + ' ' +
CONVERT(VARCHAR, CAST(#StartDate AS TIME), 108) +
CASE WHEN DATEPART(HOUR, #StartDate) < 12 THEN ' AM' ELSE ' PM' END;
N.B. As others have pointed out, you would be better off using ISO format for input dates.
Updated dateformat from DMY to MDY and explicitly adding AM/PM to the end.
What format string will do this?
Monday, May 5th 2014
Is there a simple way to do it?
I've looked at various combinations of CONVERT.
FORMAT only works in 2008
Convert has a "secret option". Convert(Varchar(20), mydate, 103). See Convert formats for a lot of other options.
See: http://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
Not exactly what you are looking for but somewhat close...
DECLARE #Date DATETIME;
SET #Date = GETDATE();
SELECT DATENAME(DW,#Date) + ', '
+ DATENAME(MONTH, #Date)
+ RIGHT(CONVERT(VARCHAR(12), #Date, 107), 9)
RESULT: Monday, May 05, 2014
Another Option:
SELECT DATENAME(DW,#Date) + ', '
+DATENAME(MONTH, #Date) + ' '
+ CAST(DAY(#Date) AS VARCHAR(2))
+ ' ' + CAST(YEAR(#Date) AS NVARCHAR(4))
RESULT: Monday, May 5 2014
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())
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.