Sql server 在变量中创建动态查询
我正在sql server 2005存储过程中创建一个动态查询,如果 将空/空日期发送到存储过程:Sql server 在变量中创建动态查询,sql-server,database,sql-server-2008,sql-server-2005,Sql Server,Database,Sql Server 2008,Sql Server 2005,我正在sql server 2005存储过程中创建一个动态查询,如果 将空/空日期发送到存储过程: This input parameter cannot be converted 那么,如何在存储过程中签入covert only id date不为空: 下面是我的问题。我已经在if条件中检查了null,但是它也显示了错误 If @startDate IS NOT NULL AND @endDate is Not null Begin set @strCondit
This input parameter cannot be converted
那么,如何在存储过程中签入covert only id date不为空:
下面是我的问题。我已经在if条件中检查了null,但是它也显示了错误
If @startDate IS NOT NULL AND @endDate is Not null
Begin
set @strCondition = ' FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,@startDate,112) + ''') and FO.Rf_Date<= convert(datetime, ''' + Convert(varchar,@endDate,112) + ''')'
End
如果@startDate不为NULL且@endDate不为NULL
开始
设置@strCondition='FO.Rf_Date>=convert(datetime,'+convert(varchar,@startDate,112)+'')和FO.Rf_Date如果它们可以为空或null,则还需要排除空变量,例如
IF NULLIF(@startDate, '') IS NOT NULL AND NULLIF(@endDate, '') IS NOT NULL
您还可以将ISDATE()函数与CASE语句一起使用,如下所示
SET @strCondition = N' SELECT * FROM TableName WHERE 1 = 1 ' --<-- 1 = 1 so you can append any more line starting with 'AND'
+ CASE WHEN ISDATE(NULLIF(@startDate,'')) = 1
THEN N' AND FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,@startDate,112) + ''') '
ELSE N'' END
+ CASE WHEN ISDATE(NULLIF(@endDate,'')) = 1
THEN N' AND FO.Rf_Date <= convert(datetime, ''' + Convert(varchar,@endDate,112) + ''')'
ELSE N'' END
SET@strCondition=N'从TableName中选择*,其中1=1'--