SQL Convert date - sql-server

declare #vaultdate varchar(10)
set #vaultdate = convert(date, getdate())-1
print #vaultdate
I got an error
Operand type clash: date is incompatible with int
Can someone see what I have done wrong? Thank you

Presumably, you are using SQL Server. If you want to work with dates, then use dates and their functions:
declare #vaultdate date;
set #vaultdate = dateadd(day, -1, convert(date, getdate()));
print #vaultdate;

I have updated the query, this will give you yyyy-mm-dd format
declare #vaultdate varchar(12)
set #vaultdate = getdate()-1
print CAST(convert(varchar,#vaultdate,20) AS DATE)

You have 1 parenthesis wrong and also you need to declare your variable as datetime. You don't even need convert:
declare #vaultdate datetime
set #vaultdate = getdate()-1
print #vaultdate

Gordon Linoff is totally correct when working with dates use date datatypes. Using correct datatypes is one of the foundations of good SQL design.
If you need to convert the date to a string this should be done at point of use i.e. the presentation layer otherwise you can end up converting the date to a varchar for presentation then the presentation layer converting it to a separate format again because the requirements changed.
If you absolutely have to use a varchar then just add a couple of lines to Gordons very correct answer.
declare #vaultdatestring varchar(10);
declare #vaultdate date;
set #vaultdate = dateadd(day, -1, convert(date, getdate()));
print #vaultdate;
set #vaultdatestring = convert(varchar(10), #vaultdate,103)
print #vaultdatestring;
There is a good resource on date formatting here: Date and Time Conversions Using SQL Server
If you could tell us why the varchar is needed we may be able to provide better suggestions.

Related

Trouble formatting date and time values in SQL Server in a T-SQL stored procedure

I have a simple stored procedure where part of it I want to set 2 variables, 1 for the current time and the other for the current date. I need them in hhmm format for the time and yyyyMMdd format for the date.
Here is the code I have so far:
BEGIN
DECLARE #d AS DATETIME
DECLARE #t as TIME
SET #d = GETDATE()
SET #t = SYSDATETIME()
But everything I've tried to use to change the format of those 2 variables does not help me out. The only examples I've found online is for formatting values in regular queries.
Can anyone point me in the right direction as far as what I should do to get these values? Thanks in advance.
If 2012+ you can use Format()
Example
DECLARE #d as varchar(8) = format(GetDate(),'yyyyMMdd')
DECLARE #t as varchar(4) = format(SYSDATETIME(),'HHmm') -- use hh for 12 hour time
Select #d,#t
Returns
(No column name) (No column name)
20180511 1738
For 2005
DECLARE #d as varchar(8) = convert(varchar(10),GetDate(),112)
DECLARE #t as varchar(8) = replace(left(convert(varchar(25),SYSDATETIME(),108),5),':','')

Getting the current date in SQL Server

I searched but wasn't able to find the way to get the date in this format (DD.MM.YYYY)
Help me please change this request:
DECLARE #date datetime
set #date = '01.05.2016'
SELECT [User], cast(DATEADD(SECOND, sum(datediff(DAY, #date,[Start])),#date) as date)'Date'
,cast(DATEADD(SECOND, sum(datediff(SECOND, '00:00:00',[Period])),'00:00:00') as time)'Total time'
FROM [Table].[TableAction]
where
[Start] >= #date+'00:00:00' and [Start] <= #date+'23:59:59'
group by [USER]
DECLARE #date datetime set #date = GETDATE()
Now to output it, you need to "Format" it.
select FORMAT (#date,'MM.dd.yy') as date
The best practice is to store the datetime in datetime format in the database and whenever you need the data you can access it and format it according to your need.
DECLARE #Currentdate DATETIME;
SET #Currentdate=GETDATE(); -- Store cuurent date into variable
And then when you want to display it use the below to format it as dd.MM.YYYY
SELECT CONVERT(VARCHAR(10),GETDATE(),104); -- format the #Currentdate to the required format.
FORMAT works only in SQL Server 2012+. If your database is SQL server 2008 or 2005 FORMAT doesn't work.In that case, you can go for the CONVERT function.
So, If your database is above SQL SERVER 2012, you can go for FORMAT as suggested by Tschallacka
DECLARE #Currentdate DATETIME=GETDATE(); -- Store cuurent date into variable
And then when you want to display it use the below to format it as dd.MM.YYYY
SELECT FORMAT(#Currentdate,'dd.MM.yyyy') -- format the #Currentdate to the required format.

Converting String field to a custom datetime format in SQL Server

I have a field which is a string that contains a date and time, what I do is I substring the field so I could only get the date, where the output looks like this:
2015-03-05 01:00
But I need to convert this to a date format similar to this:
05-Mar-2015 01:00
How do I convert it in SQL Server? This is my current syntax:
SELECT Convert(nvarchar(50),SUBSTRING(TT.FlightArrDate,1,10))+' '+Convert(nvarchar(5),SUBSTRING(TT.FlightArrDate,12,16))as actDateT from tabl1
Is it possible for me to change the date format and at the same time retain the time that it is being concatenated into?
I am using SQL Server 2008
Query
DECLARE #dt VARCHAR(20) = '2015-03-05 01:00'
SELECT REPLACE(CONVERT(VARCHAR(20),CAST(#dt AS DATETIME),106),' ','-')
+' '
+CONVERT(VARCHAR(20),CAST(#dt AS DATETIME),108) AS actDateT;
You can use code like this:
DECLARE #str VARCHAR(20) = '2015-03-05 01:00'
SELECT CONVERT(VARCHAR(20),CAST(#str AS DATETIME),13)
But without character "-" between date parts. Is symbol "-" necessary in your result?
Changing the datetime string into a real datetime, then formatting from there should give you what you want.
declare #d varchar(32)
set #d = '2015-03-05 01:00'
SELECT Convert(nvarchar(50),SUBSTRING(#d,1,10))+' '+Convert(nvarchar(5),SUBSTRING(#d,12,16)) as actDateT
select format(convert(datetime, #d, 120), 'dd-MMM-yyyy hh:mm')

convert datetime error in SQL Server (2005)?

I have created two functions to work with ISO 8601 dates:
CREATE FUNCTION IPUTILS_STR_TO_ISODATE (
#isostr VARCHAR(30))
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, #isostr, 126);
END;
GO
CREATE FUNCTION IPUTILS_ISODATE_TO_STR (
#date VARCHAR(30))
RETURNS VARCHAR(30)
AS
BEGIN
DECLARE #result VARCHAR(30);
SET #result = CONVERT(VARCHAR(30), #date, 126);
RETURN #result;
END;
GO
I don't get them working correct for some reason. If I do:
select dbo.IPUTILS_ISODATE_TO_STR(dbo.IPUTILS_STR_TO_ISODATE('1965-04-28T12:47:43'));
I get:
apr 28 1965 12:47PM
instead of:
1965-04-28T12:47:43
if I do:
select convert(VARCHAR(30), dbo.IPUTILS_STR_TO_ISODATE('1965-04-28T12:47:43'), 126);
I get:
1965-04-28T12:47:43
Is this a bug or am I doing something wrong?
Why are you not testing these functions individually first and then in combination? If you do test them individually you will likely see the problem ;-). Check the datatype of the #date input parameter on the IPUTILS_ISODATE_TO_STR function: it is VARCHAR(30) instead of DATETIME.
Having the incorrect datatype for the input parameter means that an implicit conversion from a real DATETIME into VARCHAR, but without a specified "style", is happening as the value comes into the function. This is the same as doing CONVERT(VARCHAR(30), #date). And the result of this implicit conversion (i.e. the value stored in #date) is being sent to the SET #result = CONVERT(VARCHAR(30), #date, 126); line.
Also, I would suggest not doing this in the first place (i.e. creating either of these functions) if they are going to be used in SELECT statements or WHERE clauses. Using the CONVERT() function in those places is repetitive, but also much faster. T-SQL scalar UDFs and Multiline TVFs do not perform well and you can slow down your queries by using them. In this particular case there is no real computation / formula being done so you aren't really gaining much outside of not needing to remember the "style" number. Also, T-SQL functions invalidate the query from getting a parallel execution plan. But if these are just being used in simple SET statements to manipulate a variable that is being used in a query, then that should be fine.

First Stored Procedure - Can't get variable to work

This is my first shot at writing a stored procedure. I'm trying to get a list of all orders placed between two dates. I would run this proc monthly, getting the orders for the trailing 6 months. If I ran it on the 2nd or the 15th of the month, it would still take the previous 6 months from the end of the previous month.
Here's the code:
CREATE PROCEDURE pMonthlyCustomerReport
-- Get the last day of the previous month and the first day of 6 months ago
#enddate date,
#startdate date
AS
SET #enddate = DATEADD(D,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0));
SET #startdate = DATEADD(M, DATEDIFF(MONTH, 0, GETDATE())-6, 0);
-- Get orders for the past 6 months
SELECT acct_num, date as OrderDate, type as OrderType
INTO #Orders
FROM rders
WHERE date BETWEEN #startdate AND #enddate;
When I run the proc, I get this error message:
Procedure or function 'pMonthlyCustomerReport' expects parameter '#enddate', which was not supplied.
Any suggestions or best practices I should be using here? I may be over-thinking creating the #enddate, #startdate and should just put them in the query, but I want the variable to be declared up front.
Any thoughts?
Thanks
You can just declare the vars #startdate and #enddate instead of making them parameters to the sp, since you are setting them based on the current date anyway:
DECLARE #startdate datetime
DECLARE #enddate datetime
then declare it like this:
CREATE PROCEDURE pMonthlyCustomerReport
AS
You have two problems here. The first one is that you are declaring input parameters that you are not supplying values for(which is obviously not your intention). Solution: Put them after the AS and use DECLARE to declare them as local variables.
The second problem is that you are trying to set a value of the declared input parameters. This problem will be solved with the first change.
Put
declare #enddate date
declare #startdate date
after the
AS
so they are not declared as parameters that have to be supplied when calling the procedure.
You are asking for parameters, change #enddate and #startdate to local variables by using declare statements.

Resources