当前位置: 代码迷 >> Sql Server >> 储存过程如何让一条带有变量的SQL语句在变量前后加单引号
  详细解决方案

储存过程如何让一条带有变量的SQL语句在变量前后加单引号

热度:24   发布时间:2016-04-27 14:40:32.0
储存过程怎么让一条带有变量的SQL语句在变量前后加单引号
ALTER PROCEDURE [dbo].[proc_business]
[email protected] varchar(20),
[email protected] varchar(20),
AS

BEGIN
 declare @wheretrue varchar(100)
 if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where [email protected]+''
 else set @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+''

 select * from P_BUSINESS_LIST where DEPT_CODE in (@wheretrue)
END

[email protected]件,条件是产生了
select DEPT_CODE from T_DEPT where BRANCH_CODE=HGZL002
可是BRANCH_CODE,USER_NO这两个字段是varchar类型的,所以产生出来的SQL因为少了两个单引号怎么也查不到值。

------解决方案--------------------
SQL code
set @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+''''
------解决方案--------------------
SQL code
if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where [email protected]+'''' else set @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+''''
------解决方案--------------------
SQL code
ALTER PROCEDURE [dbo].[proc_business][email protected] varchar(20),[email protected] varchar(20),ASBEGIN declare @wheretrue varchar(100) if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where USER_NO='''+ltrim(@user)+'''' else set @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+'''' select * from P_BUSINESS_LIST where DEPT_CODE in (' +ltrim(@wheretrue)+ ')END
------解决方案--------------------
SQL code
ALTER PROCEDURE [dbo].[proc_business][email protected] varchar(20),[email protected] varchar(20),ASBEGIN declare @wheretrue varchar(100) if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where USER_NO='''+ltrim(@user)+'''' else set @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+'''' exec('select * from P_BUSINESS_LIST where DEPT_CODE in (' +ltrim(@wheretrue)+ ')')END
------解决方案--------------------
SQL code
ALTER PROCEDURE [dbo].[proc_business](@user varchar(20),@city varchar(20))ASBEGINdeclare @wheretrue varchar(100)if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where USER_NO='''+ltrim(@user)+''''elseset @wheretrue ='select DEPT_CODE from T_DEPT where [email protected]+''''exec('select * from P_BUSINESS_LIST where DEPT_CODE in (' [email protected]+ ')')END
------解决方案--------------------
双引号外面套单引号 '"+xxxxx+"'
  相关解决方案