日期:2014-05-18  浏览次数:20448 次

储存过程怎么让一条带有变量的SQL语句在变量前后加单引号
ALTER PROCEDURE [dbo].[proc_business]
 @user varchar(20),
 @city varchar(20),
AS

BEGIN
 declare @wheretrue varchar(100)
 if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where USER_NO='+@user+''
 else set @wheretrue ='select DEPT_CODE from T_DEPT where BRANCH_CODE='+@city+''

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

我是想根据@city这个参数有没有值来产生不同的条件,条件是产生了
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 BRANCH_CODE='''+@city+''''

------解决方案--------------------
SQL code
if(@city='') set @wheretrue='select DEPT_CODE from T_USERDEPT where USER_NO='''+@user+''''
 else set @wheretrue ='select DEPT_CODE from T_DEPT where BRANCH_CODE='''+@city+''''

------解决方案--------------------
SQL code
ALTER PROCEDURE [dbo].[proc_business]
 @user varchar(20),
 @city varchar(20),
AS

BEGIN
 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 BRANCH_CODE='''+@city+''''

 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),
AS

BEGIN
 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 BRANCH_CODE='''+@city+''''

 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)
)
AS

BEGIN
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 BRANCH_CODE='''+@city+''''
exec('select * from P_BUSINESS_LIST where DEPT_CODE in (' +@wheretrue+ ')')
END

------解决方案--------------------
双引号外面套单引号 '"+xxxxx+"'