将varchar值'2018-01-01'转换为数据类型int时转换失败

时间:2018-10-31 07:11:35

标签: sql-server

ALTER procedure [dbo].[USP_xyz]
AS
declare 
@date varchar(100),
@conditiondate varchar(100);

SET @date = (SELECT top 1 column1 from mytable ORDER BY column1 DESC);

set @conditiondate = SUBSTRING(@date,1,10) ;
SELECT CONVERT(INT, @conditiondate) ;

print @conditiondate
return @conditiondate;
GO

1 个答案:

答案 0 :(得分:0)

这是引发错误的语句

SELECT CONVERT(INT, @conditiondate)

如果您尝试获取日期的任何部分(如月,日或年),则在SQL Server中已为此内置了功能

SELECT 
DAY(GETDATE()),--To Get the Date
MONTH(GETDATE()),--To get The Month
YEAR(GETDATE())--To Get the Year

或者如果您尝试根据某种特定格式进行格式化,请尝试这样

SELECT FORMAT(GETDATE(),'MMMDDYYYY')