【问题标题】:SQL query does not return any dataSQL查询不返回任何数据
【发布时间】:2020-07-30 15:14:26
【问题描述】:

我正在尝试测试存储过程中使用的查询。

该存储过程是从另一个用于工作的数据库复制而来的。

存储过程将接受一个参数yyyymm,例如202006

它有一个查询,该查询使用来自该参数的substrings 来表示月份和年份。

这就是计算月份和年份数据的方式:

declare @themonth nvarchar(15) = '202006'

declare @month nvarchar(5)
set @month = substring(@themonth,5,2)

declare @year nvarchar(5)
set @year= substring(@themonth,1,4)

当为202006 选择数据时,我正在获取该参数的所有记录。

所以,这里是逻辑的一些部分。我不需要在这里写整个查询。 我将只提供一些伪代码:

Select top 10000 mmi.theMonth, *
from (here we have inner joins)

where mmi.theMonth = @theMonth

执行该操作时,我得到:

theMonth   rptdate
202006     2020-06-30 00:00:00.000

rptdate 是日期数据类型 月份是 nvarchar(6)

现在,当向该查询添加另一个条件时,不会返回任何内容。

这是一个条件:

and rptdate like @month + '%' and rptdate like '%' + @year

我不知道为什么。 2020-06-30 00:00:00.000 包含 @month = '06' and @year = '2020'

这个逻辑有什么问题?

【问题讨论】:

  • @month + '%' 将匹配以月份开头的字符串。 '%' + @year 将匹配以年份结尾的字符串。
  • rptdatedate。对它使用LIKE 是没有意义的。 date 不是 LIKE varchar。您实际上想在这里实现什么目标?

标签: sql sql-server sql-like


【解决方案1】:

您的代码中的通配符 % 的顺序错误,但您也可以这样做

where year(rptdate) * 100) + month(rptdate) = @theMonth

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-22
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多