当前位置: 代码迷 >> Sql Server >> 存儲過程中動態組裝sql語句~救命~该怎么解决
  详细解决方案

存儲過程中動態組裝sql語句~救命~该怎么解决

热度:382   发布时间:2016-04-27 19:47:08.0
存儲過程中動態組裝sql語句~~~救命~~
從外部傳進來六個參數,我要根據參數的情況來組裝sql語句!;;
類似于:
sql= "select   *   from   tablename   where   1=1 ";
if(@para1   not   is   null)
  sql=sql+ "   and   [email protected] ";
if(@para2   not   is   null)
  sql=sql+ "and   [email protected] ";
...
...

高手指教怎么寫?
或者有沒有更好的辦法,來進行處理這樣的多參數問題?

------解决方案--------------------
declare @sql varchar(1000)

set @sql= 'select * from tablename where 1=1 '
if @para1 is not null
set @[email protected]+ ' and field1= '[email protected] field1= ' ' '[email protected]+ ' ' ' '
.
.
.
------解决方案--------------------
sql= "select * from tablename where 1=1 and field1=isnull(@para1,field1) and field2=isnull(@para2,field2) "
------解决方案--------------------
declare @sql varchar(1000)
set @sql= ' '
set @sql= 'select * from tablename where 1=1 '
if(@para1 is not null)
begin
set @[email protected]+ ' and field1= ' + @para1
[email protected]*/
set @[email protected]+ ' and field1= ' ' ' + @para1 + ' ' ' '
end
.....
------解决方案--------------------
DATETIME在sql中就是一个字符串
  相关解决方案