Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 在变量中创建动态查询_Sql Server_Database_Sql Server 2008_Sql Server 2005 - Fatal编程技术网

Sql server 在变量中创建动态查询

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

我正在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 @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'--