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

Sql server 在SQL Server的convert函数中使用substring函数,sql-server,datetime,Sql Server,Datetime,SQL Server:我可以将varchar转换为子字符串,然后转换为datetime以与单个SQL查询中的datetime范围进行比较吗 我在where子句中需要这个,从技术上讲,不-不能将某个东西转换为,因为它不是。但是,如果需要,可以使用子字符串将varchar转换为datetime 以下面的例子为例 myStringWithDate ------------------------------ 'This date, 2015-01-01 08:00:00, is...' SELECT

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


我在where子句中需要这个,从技术上讲,不-不能将某个东西转换为,因为它不是。但是,如果需要,可以使用子字符串将varchar转换为datetime

以下面的例子为例

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

SELECT * FROM myTable
WHERE getDate() <= CAST(SUBSTRING(myStringWithDate, 12, 19) AS DateTime)
在本例中,子字符串将返回“2015-01-01 08:00:00”,然后将其转换为datetime以与getDate系统当前datetime进行比较


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

可以完成。T-Sql允许您将子字符串函数嵌套在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

文本中的日期格式是什么?你查过了吗?看这一页你查过了吗。你的问题有什么不同