Add characters in the variable - sql

I need to make the string/varchar variable with value 20061212 to be string/varchar value 2006-12-12 00:00:00
I can't find the right SQL syntax code to make it happened in SQL Server.
The code can be created as stored procedure or similar in SQL Server.

SELECT
LEFT(#string, 4)
+ '-' + SUBSTRING(#string, 5, 2)
+ '-' + SUBSTRING(#string, 7, 2)
+ ' 00:00:00'
You could cast your string to a DATETIME and then convert it back to a string in your chosen format. But that would likely be slower than this more explicit option.
SELECT
CONVERT(VARCHAR(19), CAST(#string AS DATETIME), 120)

You can use stuff
declare #s varchar(8) = '20061212'
select stuff(stuff(#s, 7, 0, '-'), 5, 0, '-')+' 00:00:00'

You can use the SUBSTRING() function (detailed here: http://www.sql-statements.com/sql-substring.html) to take apart the original string, and then put the pieces back together with the added dashes & time at the end using the concatenation operator +.

Culture independent variant:
SELECT CONVERT(varchar, convert(datetime, '20061212', 112), 120)
BUT this only valid for DATETIME-allowed range of dates, use DATETIME2 instead

Related

Possible to avoid repetition of expression in a QUERY

I have to display time in a weird format.
For example, if time is 15:30:45.5000, I need to display "153045.5".
To do this, I have the following query:
SELECT LEFT(CONVERT(varchar(20), GETDATE(), 114), 2) +
SUBSTRING(CONVERT(varchar(20), GETDATE(), 114), 4, 2) +
SUBSTRING(CONVERT(varchar(20), GETDATE(), 114), 7, 2) + '.' +
SUBSTRING(CONVERT(varchar(20), GETDATE(), 114), 10, 1);
Is there anything I can do to avoid repeating the expression CONVERT(varchar(20), GETDATE(), 114)?
Edit:
I saw a really cool answer here which was deleted for some reason after I refreshed the page, but it gave me the idea to think of an alternative solution:
SELECT REPLACE(RIGHT(CONVERT(varchar(21), getdate(), 126), 10), ':', '')
Although this answer doesn't solve the original question in a generic way, it still solves my problem in a different way.
In addition to functions in other answers, you can calculate a partial result in a common table expression (CTE) or inline view:
; WITH gd(getDate_114)
AS (SELECT CONVERT(VARCHAR(20), GETDATE(), 114))
SELECT LEFT(getDate_114, 2)
+ SUBSTRING(gd.getDate_114, 4, 2)
+ SUBSTRING(gd.getDate_114, 7, 2)
+ '.'
+ SUBSTRING(gd.getDate_114, 10, 1)
FROM gd
Unfortunately, unless I'm mistaken, there isn't a way to minimize this in SQL Server 2008 R2. You'll have to construct it the way you're already doing it. Another option (as already pointed out by #jonasnas) would be to create a function that returns the format of the current date.
If you are able/willing to upgrade to SQL Server 2012, however, you can take advantage of the FORMAT() function to format the string:
Select Format(GetDate(), N'HHmmss.f')
Wrap all the formatting code in a function
create function dbo.FormatTime (#time datetime)
returns varchar(20)
as
begin
return (select LEFT(CONVERT(varchar(20), #time, 114), 2)
+ SUBSTRING(CONVERT(varchar(20), #time, 114), 4, 2)
+ SUBSTRING(CONVERT(varchar(20), #time, 114), 7, 4))
end
And use it as
select dbo.FormatTime(getdate())
To avoid repetition in the function body, you can store the #time converted to varchar in a variable
declare #dateAsVarchar varchar(20) = CONVERT(varchar(20), #time, 114)
return (select LEFT(#dateAsVarchar, 2)
+ SUBSTRING(#dateAsVarchar, 4, 2)
+ SUBSTRING(#dateAsVarchar, 7, 4))

Elegantly convert DateTime type to a string formatted "dd-mmm"

We have the following solution:
select
substring(convert(varchar(20),convert(datetime,getdate())),5,2)
+ ' ' +
left(convert(varchar(20),convert(datetime,getdate())),3)
What is the elegant way of achieving this format?
You can do it this way:
declare #date as date = getdate()
select replace(convert(varchar(6), #date, 6), ' ', '-')
-- returns '11-Apr'
Format 6 is dd mon yy and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.
You can use the dateName function:
select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate())
If you really want the mmm part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example
select left(convert(nvarchar, getDate(), 7), 3)
The problem is that dateName doesn't have an option to get you the abbreviated month, and the abbreviation isn't always just the first three letters (for example, in czech, two months start with Čer). On the other hand, convert 7 always starts with the abbreviation. Now, even with this, I assume that the abbreviation is always three letters long, so it isn't necessarily 100% reliable (you could search for space instead), but I'm not aware of any better option in MS SQL.
DECLARE #t datetime = getdate()
SELECT CONVERT(VARCHAR(24),LEFT(#t,6),113)
Try this...
SELECT LEFT(CONVERT(NVARCHAR(10), GETDATE(), 6), 6)

convert date to YYMM format in sql for given date

How can we convert date format to YYMM(ex:1208) for the given date 25/08/2012.
Use convert with style 12 and pick the first four characters.
select convert(char(4), getdate(), 12)
try this:
declare #date date='08/25/2012'
select CONVERT(varchar(4),#date,12)
You did not specify the datatype for the value 25/08/2012.
declare #dt char(10)
set #dt = '25/08/2012'
select right(#dt, 2) + substring(#dt, 4, 2)
If you don't like remembering the string convert formulas, you can also use:
declare #date date=CURRENT_TIMESTAMP
select right(CAST(year(#date) as varchar(4)), 2) + RIGHT('0'+cast(month(#date) as varchar(2)), 2)
It is a bit more cumbersome, but saves a trip to the help pages.

how to format getdate into YYYYMMDDHHmmSS

In SQL Server how do I format getdate() output into YYYYMMDDHHmmSS where HH is 24 hour format?
I've got the YYYYMMDD done with
select CONVERT(varchar,GETDATE(),112)
but that is as far as I got.
Thanks.
Just for anyone searching for this functionality that has SQL Server 2012 you can use the FORMAT function:
SELECT FORMAT ( GETDATE(), 'yyyyMMddHHmmss') AS 'Custom DateTime'
This allows any .NET format strings making it a useful new addition.
select replace(
replace(
replace(convert(varchar(19), getdate(), 126),
'-',''),
'T',''),
':','')
Close but not exactly what you are asking for:
select CONVERT(varchar, GETDATE(), 126)
e.g.
2011-09-23T12:18:24.837
(yyyy-mm-ddThh:mi:ss.mmm (no spaces), ISO8601 without timezone)
Ref: CAST and CONVERT
There is no way to specify a custom format with CONVERT(). The other option is to perform string manipulation to create in the format you desire.
Try this:
select CONVERT(varchar, GETDATE(), 120)
e.g.
2011-09-23 12:18:24
(yyyy-mm-dd hh:mi:ss (24h) ,ODBC canonical).
Hth.
Another option!
SELECT CONVERT(nvarchar(8), GETDATE(),112) +
CONVERT(nvarchar(2),DATEPART(HH,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(MI,GETDATE())) +
CONVERT(nvarchar(2),DATEPART(SS,GETDATE()));
converting datetime that way requires more than one call to convert. Best use for this is in a function that returns a varchar.
select CONVERT(varchar,GETDATE(),112) --YYYYMMDD
select CONVERT(varchar,GETDATE(),108) --HH:MM:SS
Put them together like so inside the function
DECLARE #result as varchar(20)
set #result = CONVERT(varchar,GETDATE(),112) + ' ' + CONVERT(varchar,GETDATE(),108)
print #result
20131220 13:15:50
As Thinhbk posted you can use select CONVERT(varchar,getdate(),20) or select CONVERT(varchar,getdate(),120) to get quite close to what you want.
select CONVERT(nvarchar(8),getdate(),112) +
case when Len(CONVERT(nvarchar(2),DATEPART(HH,getdate()))) =1 then '0' + CONVERT(nvarchar(2),DATEPART(HH,getdate())) else CONVERT(nvarchar(2),DATEPART(HH,getdate())) end +
case when Len( CONVERT(nvarchar(2),DATEPART(MI,getdate())) ) =1 then '0' + CONVERT(nvarchar(2),DATEPART(MI,getdate())) else CONVERT(nvarchar(2),DATEPART(MI,getdate())) end

SQL Server String Parsing

I have SQL Server 2005 and all dates are stored using a DATETIME column type. The front-end application handles dates in a "yyyyMMdd hhmmss" format. I'm writing a set of SQL queries and stored procedures and was wondering if there is an easy way to convert this format to the standard SQL DATETIME. I did not code the front-end app so I cannot make any changes to it.
I have looked into CONVERT(), but none of the type codes match what I want. The closest one is
CONVERT(DATETIME, '20101017' 112)
But that does not have the time component of the input. Any ideas? or do I have to write a SQL function to do that parsing and conversion.
Thank you,
If you insert the colons into the appropriate places in your time, you can use style 120.
declare #d varchar(15)
set #d = '20101017 111428'
select CONVERT(DATETIME, stuff(stuff(#d,12,0,':'),15,0,':'), 120)
You might find this page to be useful (if you can get past the psychosis-inducing color scheme).
How about this:
declare #s as varchar(25)
set #s = '20101109 172054'
select #s, convert(datetime, SUBSTRING(#s, 1, 4) + '-' + SUBSTRING(#s, 5, 2)
+ '-' + SUBSTRING(#s, 7, 3) + SUBSTRING(#s, 10, 2) + ':'
+ SUBSTRING(#s, 12, 2) + ':' + SUBSTRING(#s, 14, 2), 20)