存储过程LIKE参数操作

时间:2017-01-19 09:47:00

标签: sql-server excel stored-procedures

我有一个Excel,我使用Microsoft Query连接到我的存储过程。

我的程序如下:

IgnoreAndReport(m => m.SomeProperty);

我的目标是设置日期时间列ALTER PROCEDURE [dbo].[WatchDogDataCollector] @websiteID int = NULL, @FailureLogStart datetime = NULL, @FailureLogEnd datetime = NULL AS SELECT * FROM WATCHDOG.WatchdogUsr.WebsiteFailureLog WHERE websiteID = ISNULL(@websiteID,websiteID) AND (((FailureLogStart LIKE '%' + ISNULL(@FailureLogStart, FailureLogStart) + '%'))) AND (((FailureLogEnd LIKE '%' + ISNULL(@FailureLogEnd, @FailureLogEnd) + '%'))) & FailureLogStart 有可选的。

到目前为止,一旦与Excel连接这么好,我试图用一些动态参数运行我的存储过程,我收到一条错误消息:

  

[Microsfot] [ODBC SQL Server驱动程序] [SQL Server]转换失败时   从包机字符串转换日期和/或时间

我不确定如果我在Excel或SQL中做错了什么?

2 个答案:

答案 0 :(得分:0)

将参数作为varchars传递它们不是完整日期:

ALTER PROCEDURE [dbo].[WatchDogDataCollector] @websiteID int = NULL, @FailureLogStart datetime = NULL, @FailureLogEnd datetime = NULL
AS 
SELECT * 
FROM WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE websiteID  = ISNULL(@websiteID,websiteID)
AND (((cast(FailureLogStart as varchar(50)) like '%'+ISNULL(@FailureLogStart, cast(FailureLogStart as varchar(50)))+'%'))) 
AND (((cast(FailureLogEnd as varchar(50)) like '%'+ISNULL(@FailureLogEnd, cast(FailureLogEnd as varchar(50)))+'%')))

答案 1 :(得分:0)

通过关注错误消息和查询,我认为应该有数据类型不匹配,因为like运算符是一个字母数字过滤器,即它采用字符串类型。所以,这应该工作

ALTER PROCEDURE [dbo].[WatchDogDataCollector] 
    @websiteID int = NULL, 
    @FailureLogStart datetime = NULL, 
    @FailureLogEnd datetime = NULL
AS 
SELECT 
    * 
FROM 
    WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE 
    websiteID  = ISNULL(@websiteID,websiteID)
    AND (((CONVERT(NVARCHAR(20), FailureLogStart) LIKE '%' + CONVERT(NVARCHAR(20), ISNULL(@FailureLogStart, FailureLogStart)) + '%'))) 
    AND (((CONVERT(NVARCHAR(20), FailureLogEnd) LIKE '%' + CONVERT(NVARCHAR(20), ISNULL(@FailureLogEnd, FailureLogEnd)) + '%'))) 

但是这会将datetime列数据转换为nvarchar。

相反,您也可以将数据时间数据格式化为int类型然后进行比较。 例如。 SELECT CONVERT(VARCHAR(35),GETDATE(),112)。 如果还创建了索引,这将比字符串搜索有效。

像:

ALTER PROCEDURE [dbo].[WatchDogDataCollector] 
    @websiteID int = NULL, 
    @FailureLogStart nvarchar(40) = NULL, -- datetime Changed to allow "2016" in search text box.
    @FailureLogEnd nvarchar(40) = NULL -- datetime
AS   

SELECT 
    * 
FROM 
    WATCHDOG.WatchdogUsr.WebsiteFailureLog
WHERE 
    websiteID  = ISNULL(@websiteID,websiteID)
    AND (((CONVERT(NVARCHAR(35), FailureLogStart, 112) LIKE '%' + CONVERT(NVARCHAR(35), ISNULL(@FailureLogStart, FailureLogStart), 112) + '%'))) 
    AND (((CONVERT(NVARCHAR(35), FailureLogEnd, 112) LIKE '%' + CONVERT(NVARCHAR(35), ISNULL(@FailureLogEnd, FailureLogEnd), 112) + '%')))