SQL Server : split string in SELECT statement - sql

I want to split date in column in 3 fields, I use this query
SELECT
SUBSTRING(Account.date, 1, 2) AS "Month",
SUBSTRING(Account.date, 4, 2) AS "Day",
SUBSTRING(Account.date, 7, 4) AS "Year"
FROM Account
Almost all data is in format 02/11/2000, but some of it can be 02/November/2000 or 2/11/2000.
Only common thing is that data separated by /. How can I separate this column using the delimiter?

Surprisingly CAST('2/November/2000' as datetime) works (checked on SQL Server 2008), gives value 2000-11-02 00:00:00.000
SELECT
Month(CAST(Account.date AS DateTime)) "Month",
Day(CAST(Account.date AS DateTime)) "Day",
Year(CAST(Account.date AS DateTime)) "Year",
FROM Account
But as rightly pointed out in comment how do you know if "02/11/2000" is November 2, 2000 or February 11, 2000?
Also the spelling of Month names must be absolutely correct else conversion fails. Since you are storing dates as string there is chance that entry like November , Agust etc could have been made .
You should never store date values as strings.

You can do it this way by using CHARINDEX and SUBSTRING functions
select
LEFT(Account.date, CHARINDEX('/', Account.date) - 1),
SUBSTRING(Account.date, CHARINDEX('/', Account.date) + 1, LEN(Account.date) - CHARINDEX('/', Account.date) - CHARINDEX('/', Account.date, CHARINDEX('/', Account.date)) - 2),
REVERSE(LEFT(REVERSE(Account.date), CHARINDEX('/', REVERSE(Account.date)) - 1))
FROM Account

You can abuse the PARSENAME function slightly here:
SELECT FirstPart = PARSENAME(REPLACE(Account.Date, '/', '.'), 3),
SecondPart = PARSENAME(REPLACE(Account.Date, '/', '.'), 2),
ThirdPart = PARSENAME(REPLACE(Account.Date, '/', '.'), 1)
FROM (VALUES
('02/November/2000'),
('2/11/2000')
) Account (Date);
Will give:
FirstPart SecondPart ThirdPart
02 November 2000
2 11 2000
I would however, highly recommend storing your dates using the appropriate data type!. SQL Server 2012 has the TRY_CONVERT function which can make such conversions easier, but you still need to know what format your string date is in, 2/11/2000 could be the 2nd November, or 11th February depending on your regional settings.

You can use the combination of CharIndex and Substring function in SQL to split the string based on delimiter.
You can check CharIndex examples here SQL Server 2005 Using CHARINDEX() To split a string
and here SQL Server - find nth occurrence in a string

Assuming your database column account.date contains a valid datetime or date value you should using SQLServers date functions like:
select month(getDate()) as "Month",
day(getDate()) as "Day",
year(getDate()) as "Year"
I replaced your column account.date by a getDate() to have some test values. This maps to your SQL in the following way
SELECT
month(Account.date) AS "Month",
day(Account.date) AS "Day",
year(Account.date) AS "Year"
FROM Account
Storing these date values as varchars would be IMHO a design flaw of your database structure. Dates are formatted in multiple ways to text. This is the presentation of your database data. To process your data you would always preprocess your text dates. That is bad practice.
If you have indeed varchar values there are several SO questions like: How do I split a string so I can access item x?.

Try this:
DECLARE #VALUE VARCHAR(100)<BR>
SET #VALUE ='2/11/2000' <BR>
SELECT SUBSTRING(#VALUE,0,CHARINDEX('/',#VALUE,0)),
SUBSTRING(#VALUE,
CHARINDEX('/',#VALUE,0)+1,
(CHARINDEX('/',#VALUE,(CHARINDEX('/',#VALUE,0)+1)) -
CHARINDEX('/',#VALUE,0) - 1)
),RIGHT(#VALUE,4)

Related

convert date in string format to date datatype sql

I have values in a column named Date as a nvarachar data type in the form of mmddyy and want to convert the values to a date datatype in the form of yyyy-mm-dd, what sql colde can I use to convert the value.
example
02121955 -> 1955-02-12
You can use datefromparts():
select datefromparts(right(str, 4), left(str, 2), substring(str, 3, 2))
Or reconstruct it as yyyymmdd format and just convert:
select convert(date, left(right(str, 4) + str, 8))
Here is a db<>fiddle.
I have found a similar Question to yours that has been solved: https://stackoverflow.com/a/39139155/14940878
Here is the Code changed for your requests:
declare #date varchar(max)='02121955'
select convert(varchar(8),cast(CONCAT(SUBSTRING(#date,5,4),'/',SUBSTRING(#date,1,2),'/',SUBSTRING(#date,3,2)) as date),112)as [YYYYMMDD]
You need to take each field and concat it into one and then convert it to datetime.
SUBSTRING(#date,5,4) - Takes the last four characters.
SUBSTRING(#date,1,2) - Takes the first two.
SUBSTRING(#date,3,2) - Takes the two in the middle.
Assuming it's SQL Server, I think you just need
select cast(format(02121955,'##-##-####') as date)
DEMO

How to i get Month & Year from SQL in Varchar Type

I Already Created Table (commercials) Column (MyDate) "Varchar(255)"
I Have some manual entries like:
dd-mm-yyyy
01-05-2019
02-05-2019
15-06-2019
16-06-2019
Now i want to select Only One Month and year. like
05-2019 or 06-2019
Please tell me how i can select only Month and year from this column.
You don't need any conversion among data types, since you want to extract a string from string, and to extract the part with mm-yyyy format pattern, just use substring() function as below :
select distinct substring(replace(MyDate,' ',''), 4, 7) as "Month-Year"
from myTable;
Month-Year
----------
05-2019
06-2019
By the way, consider using replace(MyDate,' ','') (trim(MyDate) for version 2017+) against the probabilty of having space within the strings.
Use string operations:
select right(col, 4) as yyyy,
right(col, 7) as mmyyyy,
substring(col, 4, 2) as mm
Using DISTINCT on Only MM-YYYY part of your data will return a MM-YYYY combination only once as per your requirement. Sample script is shown below-
SELECT DISTINCT RIGHT(MyDate, 7)
FROM commercials

SQL Varchar convert to Date - Sybase

I am using Sybase IQ and have the following stored as a varchar:
01October 2010
I want to convert this from varchar to date datatype with the following format:
yyyy-mm-dd eg.2010-10-01
How would I write this SQL statement? Thanks in advance.
With difficulty. There's a reason you should never store dates and times as strings.
It's been awhile since I've used Sybase, but what we need to do is get the field into YYYY-MM-DD format, and then pass it to the DATE() or DATETIME() function.
Let's assume the first two characters are always the day of the month, and the last 4 characters are the year. That means everything in between is the month. Let's also assume that there are no leading or trailing spaces. If either of these assumptions fails, then the query will fail.
Then you can do something like this:
SELECT DATE (
RIGHT(UnnamedField,4) + '-' +
CASE LTRIM(RTRIM(SUBSTRING(Unnamed,3,LEN(Unnamed) - 6)))
WHEN 'January' THEN '01'
WHEN 'February' THEN '02'
WHEN 'March' THEN '03'
.
.
.
WHEN 'December' THEN '12'
END + '-' + LEFT(UnnamedField,2)
)
FROM UnnamedTable
Note that, as others have mentioned, the date data type is not a formatted datatype. If possible you should format it in your application. If you must do it in the query, use the CONVERT() function.
Sybase is able to convert a string to a date. So if you use substring to extract the date into a format that IQ can convert, then you can just use the convert() function.
Here's an example of how to do it:
Sample data:
create table #tmp1 (col1 varchar(100))
insert #tmp1 values ('01October 2010')
Query to convert the value to a date:
select
convert
(
date,
(
substring(col1, 3, charindex(' ', col1) - 2) -- Month
+ substring(col1, 1, 2) -- Day
+ substring(col1, charindex(' ', col1), 5) -- Year (include the leading space)
)
)
from #tmp1
Now that the value is in a date format, you can use the convert function to convert the date datatype to string, using your specified format. The default output for a date datatype is yyyy-mm-dd already.
Edit: After taking a look at #BaconBits' answer, I've realized that I could simplify the query a bit by using the substring function wrappers left, right, and the convert wrapper of date. It's the same logic; but using the simplified wrappers might make it easier to understand.
select
date
(
substring(col1, 3, charindex(' ', col1) - 2) -- Month
+ left(col1, 2) -- Day
+ ' ' + right(col1, 4) -- Year (include the leading space)
)
from #tmp1

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)

How can I calculate the difference in days between two days stored as YYYYMMDD in a query?

I am writing a query where I need to calculate the number of days since a date that is stored in the database in the format "YYYYMMDD". Since this is not a Date datatype, I can't use native Date functions. What is the best way (performance-wise, readability-wise, etc.) to perform such a calculation in a SQL query.
Best? Convert that old table to use real date columns.
Next best? Write a database function to convert YYMMDD to a real date. Alan Campin's iDate can help. You'd end up with something akin to select cvty2d(date1)-cvty2d(date2) from ...
Better than nothing? Write ugly SQL to convert the number to character, split the character up, add hyphens and convert THAT to a real date. That beast would look something like
select
date(
substr(char(date1),1,4) concat
'-' concat
substr (char(date1),5,2) concat
'-' concat
substr(char(date1),7,2)
) -
date(
substr(char(date2),1,4) concat
'-' concat
substr (char(date2),5,2) concat
'-' concat
substr(char(date2),7,2)
)
from ...
Edit
The reason these gymnastics are necessary is that the DB2 DATE() function wants to see a string in the form of 'YYYY-MM-DD', with the hyphens being necessary.
Which version of SQL are you running? SQL2008 has no issues with that format as a date datatype
Declare #something nvarchar(100)
set #Something = '20120112'
select dateadd(dd, 1, #Something)
select datediff(dd, #Something, getdate())
2012-01-13 00:00:00.000
118