Convert DateTime to VarChar (without time part) in SQL Server
To convert a DateTime variable to a VarChar variable in yyyy-mm-dd format, you can use the built-in CONVERT function:
<code class="language-sql">CONVERT(VARCHAR(10), GETDATE(), 120) /* 将 'GETDATE()' 替换为您的 DateTime 变量 */</code>
This command will return the VarChar value in the specified yyyy-mm-dd format, excluding the time part.
Other styles for converting DateTime to VarChar
In addition to the 120 style, a number of other styles can be used to format output VarChar values. The following demo illustrates the various styles and their corresponding output:
<code class="language-sql">DECLARE @now DATETIME SET @now = GETDATE() SELECT CONVERT(VARCHAR(MAX), @now, style) AS output, style FROM ( SELECT 0 AS style UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14 UNION SELECT 120 UNION SELECT 121 UNION SELECT 126 UNION SELECT 127 UNION SELECT 130 UNION SELECT 131 ) AS Styles ORDER BY style;</code>
Output:
输出 | 样式 |
---|---|
Apr 28 2014 9:31AM | 0 |
04/28/14 | 1 |
14.04.28 | 2 |
28/04/14 | 3 |
28.04.14 | 4 |
28-04-14 | 5 |
28 Apr 14 | 6 |
Apr 28, 14 | 7 |
09:31:28 | 8 |
Apr 28 2014 9:31:28:580AM | 9 |
04-28-14 | 10 |
14/04/28 | 11 |
140428 | 12 |
28 Apr 2014 09:31:28:580 | 13 |
09:31:28:580 | 14 |
2014-04-28 09:31:28.580 | 120 |
2014-04-28 09:31:28.580 | 121 |
2014-04-28T09:31:28.580 | 126 |
2014-04-28T09:31:28.580 | 127 |
28/06/1435 9:31:28:580AM | 130 |
28 جمادى الثانية 1435 9:31:28:580AM | 131 |
Note that the output format can be adjusted by selecting the appropriate style parameters for the CONVERT function.
The above is the detailed content of How to Convert DateTime to VarChar in SQL Server Without the Time Component?. For more information, please follow other related articles on the PHP Chinese website!