在SQL Server的convert函数中使用substring函数

时间:2015-04-18 02:53:43

标签: sql-server datetime

SQL Server:我可以将varchar转换为子字符串,然后转换为datetime以与单个SQL查询中的datetime范围进行比较吗?

我需要where子句

2 个答案:

答案 0 :(得分:0)

从技术上讲,不行 - 您无法将某些内容转换为 substring ,因为这不是datatype。但是,如果需要,可以使用子字符串将 varchar 转换为 datetime

采取以下示例

myStringWithDate
------------------------------
'This date, 2015-01-01 08:00:00, is...'

SELECT * FROM myTable
WHERE getDate() <= CAST(SUBSTRING(myStringWithDate, 12, 19) AS DateTime)

在此示例中,子字符串将返回&#39; 2015-01-01 08:00:00&#39;然后将其转换为datetime以与getDate()(系统当前DateTime)进行比较。

我希望我能正确计算子字符串。无法验证,但它应该是正确的。

答案 1 :(得分:0)

可以做到。 T-Sql允许您将SUBSTRING函数嵌套在CAST或CONVERT函数中。

比较范围的最佳方法是比较范围的开始和结束的两个条件。

以下是一些测试数据:

Create Table VarCharDateTest --Create Table with dates embedded in a varchar string
(
vID int identity(1,1),
vDate varchar(50)
)
GO

INSERT INTO VarCharDateTest --Insert Test Values
VALUES
('The Date is 04/18/2015, a Saturday'),
('The Date is 04/19/2015, a Sunday'),
('The Date is 04/20/2015, a Monday'),
('The Date is 04/21/2015, a Tuesday')
GO

CREATE TABLE DatetimeTest --Create table with dates stored as datetime
(
dID int identity(1,1),
dDate datetime
)
GO

INSERT INTO DateTimeTest --Insert Test Values
VALUES
('4/12/2015'),
('4/13/2015'),
('4/14/2015'),
('4/15/2015'),
('4/16/2015'),
('4/17/2015'),
('4/18/2015'),
('4/19/2015'),
('4/20/2015'),
('4/21/2015'),
('4/22/2015'),
('4/23/2015')
GO

DECLARE @startDate datetime = '2015-04-18 00:00:00.000'
DECLARE @endDate datetime = '2015-04-21 00:00:00.000'

SELECT
    dID, 
    dDate, 
    vID, 
    vDate,
    cast(Substring(vDate, 12,11) as datetime) as DateConvertedFromVarchar  --explicit conversion to datetime
FROM
    DatetimeTest
INNER JOIN
    VarCharDateTest
    ON dDate = cast(Substring(vDate, 12,11) as datetime)
WHERE
    cast(Substring(vDate, 12,11) as datetime) > @startDate AND
    cast(Substring(vDate, 12,11) as datetime) < @endDate