Play in SQL · Q & A · Real Scenario Logic's

SQL Question and Answer #3

Question Pic – Try yourself before checking Answer below!

Question pic

There can be ‘n’ number of answers for the above question. Among those, Below we have given one. Please comment your other methods of doing it. Because Sharing is Caring!

From ‘Thursday, March 05 2020’ To ‘2020-03-05’

SQL Script

DECLARE @date VARCHAR(50) = 'Thursday, March 05 2020'

SELECT 
@date AS Given_Date, 
CONVERT(DATE, SUBSTRING(@date, CHARINDEX(',', @date) + 1, 30) ) AS Expected_Date;

Result Set

Step by Step SQL Script

DECLARE @date VARCHAR(50) = 'Thursday, March 05 2020'
--	STEP BY STEP Answer
SELECT 
@date AS Given_Date, --Given
CHARINDEX(',', @date)+1 AS Position, --Position of 'after(+1) 1st comma'
SUBSTRING(@date, CHARINDEX(',', @date) + 1, 30) AS Date_Part, --date after ','
CONVERT(DATE, SUBSTRING(@date, CHARINDEX(',', @date) + 1, 30) ) AS Expected_Date;

Step by Step Result Set

From ‘2020-03-05’ To ‘Thursday, March 05 2020’

SQL Script

DECLARE @Date1 DATE = '2020-03-05';

SELECT 
@Date1 AS Given_Date, 
FORMAT(@Date1,'dddd, MMMM dd yyyy') AS Expected_Date;

Result Set

NOTE-

We have tested the above scripts in SQL Server 2017. It works fine for both Azure SQL DB and On-Premises. Unit Tested as well.

Related Blog posts

Follow Blog and Show your Support for many more interesting upcoming Posts!

Advertisement

3 thoughts on “SQL Question and Answer #3

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s