How to Convert a Datetime to String in T-SQL?
To convert a datetime value to a string in T-SQL (Transact-SQL), you can use the CONVERT or CAST function. Here's an example:
sql server convert string to date
select Cast( '2021-09-22' as date ) as castedDate;
select convert(date,'20210922') as convertedDate;
sql server datetime to string
DECLARE @dt DATETIME = '2019-12-31 14:43:35.863';
SELECT
CONVERT(VARCHAR(20),@dt,0) s1,
CONVERT(VARCHAR(20),@dt,100) s2;
=========================================
OUTPUT
=========================================
s1 s2
-------------------- --------------------
Dec 31 2019 2:43PM Dec 31 2019 2:43PM
(1 row affected)
date to string sql
SELECT
TO_CHAR(SYSDATE, 'YYYY-MM-DD')
FROM
dual;
Code language: SQL (Structured Query Language) (sql)
How to Convert a Datetime to String in T-SQL?
DECLARE @DateTimeValue DATETIME = GETDATE();
DECLARE @StringValue VARCHAR(50);
-- Using CONVERT function
SET @StringValue = CONVERT(VARCHAR(20), @DateTimeValue, 120);
PRINT @StringValue;
-- Using CAST function
SET @StringValue = CAST(@DateTimeValue AS VARCHAR(20));
PRINT @StringValue;
In the above code, @DateTimeValue
is the datetime variable that you want to convert to a string. @StringValue
is the variable where the converted string will be stored.
The CONVERT function takes three arguments: the data type you want to convert to (VARCHAR in this case), the datetime value you want to convert, and the style code (120 in this case) that determines the format of the resulting string. Style code 120 represents the format "YYYY-MM-DD HH:MI:SS" (e.g., 2023-06-07 12:34:56).
The CAST function simply converts the datetime value to a VARCHAR without specifying the format explicitly. In this case, the default format will be used.
You can replace the style code (120) with a different style code to obtain the desired format. The available style codes and their corresponding formats can be found in the T-SQL documentation.
Note that the size of the VARCHAR should be sufficient to accommodate the converted string, otherwise, the result may be truncated. Adjust the size of the VARCHAR according to your needs.