在SQL Server中获取特定字符串

本文关键字:字符串 获取 SQL Server | 更新日期: 2023-09-27 18:11:40

在SQL Server 2008中,我想获得以下字符串格式的年份。参数将是以下字符串之一(c#中的DateTime.MinValueDateTime.MaxValue):

'1/1/0001 12:00:00 AM'和'12/31/9999 11:59:59 PM'

这是我期望的答案:

0001 from 1st string.
9999 from 2nd string.

在SQL Server中获取特定字符串

如果您知道输入字符串的格式,您可以这样做:

SELECT ... SUBSTRING([Input], PATINDEX('%[0-9][0-9][0-9][0-9]%', [Input]), 4)
FROM   ...

SELECT ... SUBSTRING([Input], CHARINDEX('/', [Input], 4) + 1, 4)
FROM   ...

这也可以是另一种方法。

declare @test nvarchar(50)
SET @test='1/1/9999 12:00:00 AM'
declare @testdate date
set @testdate=CONVERT(date,@test,101)
select DatePart(year,@testdate)

查看这个sqlfiddle