如果select
参数(datetime
& @StartDate
)在此存储过程中是可选的,如何在SQL Server中编写此@EndDate
查询?
CREATE PROCEDURE [dbo].[prSearchEmployees]
(
@Id INT = NULL
,@FullName VARCHAR(20) = NULL
,@Age INT = NULL
,@StartDate = NULL
,@EndDate = NULL
)
AS
BEGIN
SELECT *
FROM Employee
WHERE Id = ISNULL(@Id, Id)
AND FullName LIKE ISNULL(@FullName + '%', FullName)
AND Age = ISNULL(@Age, Age)
END
答案 0 :(得分:11)
你可以在你的sproc顶部添加两个新变量..并根据ISNULL函数分配
CREATE PROCEDURE [dbo].[prSearchEmployees]
(
@Id INT = NULL
,@FullName VARCHAR(20) = NULL
,@Age INT = NULL
,@StartDate DATETIME = NULL
,@EndDate DATETIME = NULL
)
AS
BEGIN
DECLARE @SDate DATETIME
DECLARE @EDate DATETIME
SET @SDate = ISNULL(@StartDate, GETDATE())
SET @EDate = ISNULL(@EndDate, GETDATE())
SELECT * FROM Employee
WHERE Id = ISNULL(@Id, Id)
AND FullName LIKE ISNULL(@FullName + '%', FullName)
AND Age = ISNULL(@Age, Age)
AND Date BETWEEN @SDate AND @EDate
答案 1 :(得分:6)
我知道这是一个老帖子,但有些选择更简洁。这个post完美地概括了它。因此,在前面的示例中,您将执行类似
的操作 CREATE PROCEDURE [dbo].[prSearchEmployees]
(
@Id INT = NULL
,@FullName VARCHAR(20) = NULL
,@Age INT = NULL
,@StartDate DATETIME = NULL
,@EndDate DATETIME = NULL
)
AS
BEGIN
SELECT * FROM Employee
WHERE ((@Id IS NULL) OR (Id = @Id))
AND ((@FullName IS NULL) OR (FullName LIKE @FullName + '%'))
AND ((@Age IS NULL) OR (Age = @Age))
AND ((@SDate IS NULL) OR (Date BETWEEN @SDate AND @EDate))
答案 2 :(得分:2)
AND(
((NullIf(@begin, '') IS NULL) OR CAST(ColumnDate AS DATE) >= @begin)
AND ((NullIf(@end, '') IS NULL) OR CAST(ColumnDate AS DATE) <= @end)
)
涵盖所有选项,空值,空格和比较。
答案 3 :(得分:0)
您只需要将@StartDate
和@EndDate
的数据类型定义为Date
。你可以尝试这样:
CREATE PROCEDURE [dbo].[prSearchEmployees]
(
@Id INT = NULL
,@FullName VARCHAR(20) = NULL
,@Age INT = NULL
,@StartDate DATETIME= NULL
,@EndDate DATETIME= NULL
)
AS
BEGIN
DECLARE @StDate DATETIME
DECLARE @EtDate DATETIME
SET @StDate = ISNULL(@StartDate ,NOW())
SET @EtDate = ISNULL(@EndDate , NOW())
SELECT * FROM Employee
WHERE Id = ISNULL(@Id, Id)
AND FullName LIKE ISNULL(@FullName + '%', FullName)
AND Age = ISNULL(@Age, Age)
AND Date BETWEEN @StDate AND @EtDate
END
答案 4 :(得分:0)
对于null传递到日期字段
声明dob字符串
在对象分配 stud_dtl_obj.dob = dob.Text ==&#34;&#34; ? null:dob.Text;
在程序分配 SqlHelper.MakeParam(&#34; @ DOB&#34;,obj_stud_dtl.dob),
内部程序 @dob date = NULL,