How to Convert Microsoft SQL Date to String
- 1). Open Query Analyzer or Microsoft SQL Management Console. Query Analyzer is used in SQL Server 2000. All newer versions of SQL Server use the management console.
- 2). Create a variable to hold a date. For this example, the variable "@my_date" will hold the current date and time using the "getDate()" function.
declare @my_date as datetime
set @my_date = getDate() - 3). Convert the @my_date variable using the "Cast()" function. To convert a date to a string, use the following syntax:
declare @my_date_string as varchar(20)
set @my_date_string = cast(@my_date as varchar(20))
In the statements above, the first one declares a string variable to hold the converted date. The second statement uses the cast function to convert the date and store it in the defined variable. - 4). Use the "Convert()" function to convert the date to a string. This is an alternative method also available through SQL Server. The syntax is slightly different, but the end result is still the same.
declare @my_date_string as varchar(20)
set @my_date_string = convert(varchar(20), @my_date)
The code above does the same thing as Step 3. However, the syntax for the convert statement is slightly different.
Source...