在 SQL 服务器中按日期搜索记录

Search for a record by date in SQL Server

我正在尝试制作一个文本框,每当发生文本更改事件时,该函数将使用文本框文本在数据库中搜索以找到正确的记录。

例如:我有3行(名字,phone号码,生日-格式是年-月-日-在SQL服务器中):

Name PhoneNumber Birthday
John 482 2000-7-9
Dennis 912 2001-12-9
Mike 123 2000-4-1

如果 textbox.text 是 99/,我想 return John 和 Dennis 的 2 行。

Name PhoneNumber Birthday
John 482 2000-7-9
Dennis 912 2001-12-9

如果我在文本框中输入yyyy-MM-dd格式的日期就很容易搜索,查询将是:

 SELECT * 
 FROM   database 
 WHERE  birthday LIKE %textbox.text%   

我试过了,效果很好,但只有当文本框中的日期遵循 yyyy-MM-day 格式时。它是否可以与 dd/month/yyyy 格式一起使用?

以下查询显示如何使用不同的格式选项搜索作为 'date'.
给出的值 您可以使用多个条件构建查询 WHERE ... OR ... 以匹配所有情况。
我更改了 table 的名称,因为数据库是一个保留字。
注意你不应该直接构造你的查询,以避免 SQL 注入。查找适合您使用的语言的安全方法。

declare @textboxtext VARCHAR(25);
set @textboxtext = '/9'
select * 
from data_base 
where day(birthday) 
LIKE replace(@textboxtext,'/','');
GO
name   |  id | birthday  
:----- | --: | :---------
John   | 482 | 2000-07-09
Dennis | 912 | 2001-12-09
declare @textboxtext VARCHAR(25);
set @textboxtext = '09/07/2000'
select * 
from data_base 
where birthday 
 = convert(date,@textboxtext,103);
GO
name |  id | birthday  
:--- | --: | :---------
John | 482 | 2000-07-09
declare @textboxtext VARCHAR(25);
set @textboxtext = '07/09/2000'
select * 
from data_base 
where birthday 
 = convert(date,@textboxtext,101) ;
GO
name |  id | birthday  
:--- | --: | :---------
John | 482 | 2000-07-09

db<>fiddle here

根据您的评论,这应该可以满足您的需要。注意月份必须是两位数:9/1 将匹配 9/11 但不匹配 9/01

CREATE TABLE data_base (
    name VARCHAR (25),
    id int,
    birthday date);
GO
insert into data_base values
('John', 482, '2000-7-9'),
('Dennis', 912, '2001-12-9'),
('Mike', 123, '2000-4-1');
GO

3 行受影响

declare @textboxtext VARCHAR(25);
set @textboxtext = '09/07/2000'
select * 
from data_base 
where 
convert(varchar(10),birthday,103) 
like CONCAT (@textboxtext,'%');
GO
name |  id | birthday  
:--- | --: | :---------
John | 482 | 2000-07-09
declare @textboxtext VARCHAR(25);
set @textboxtext = '9/'
select * 
from data_base 
where 
convert(varchar(10),birthday,103) 
like CONCAT ('%',@textboxtext,'%');
GO
name   |  id | birthday  
:----- | --: | :---------
John   | 482 | 2000-07-09
Dennis | 912 | 2001-12-09

db<>fiddle here