日期:2014-05-17  浏览次数:20455 次

关于SQL的拼接,单引号问题~~在线等~~着急~~

SQL code

declare @Sql varchar(1000)
declare @ACCOUNT varchar(50)='-1'  --@ACCOUNT 为 testName 时也需要符合
Set @Sql ='select * from T_ORDER where   ('+CASE @ACCOUNT WHEN '-1' THEN '1=1' ELSE 'ACCOUNT = '''+CAST(@ACCOUNT AS varchar(50)) END+''') '
select @Sql



希望高手能执行下以上这段SQL,当我传入-1时候,打印出来多一个单引号,求解阿。

如果把
SQL code
ACCOUNT = '''+CAST(@ACCOUNT AS varchar(50)) END+'''
变成
SQL code
ACCOUNT = '+CAST(@ACCOUNT AS varchar(50)) END+'
传入-1是对了,但是传入字符串用户名又缺少了单引号,在线求解~~

------解决方案--------------------
SQL code

declare @Sql varchar(1000)
declare @ACCOUNT varchar(50)='-1'  --@ACCOUNT 为 testName 时也需要符合
Set @Sql ='select * from T_ORDER where   ('+CASE @ACCOUNT WHEN '-1' THEN '''' ELSE 'ACCOUNT = '''+CAST(@ACCOUNT AS varchar(50)) END+''') '
select @Sql

------解决方案--------------------
SQL code
declare @Sql varchar(1000)
declare @ACCOUNT varchar(50)  --@ACCOUNT 为 testName 时也需要符合
set @ACCOUNT='-1'
Set @Sql ='select * from T_ORDER where   ('+CASE @ACCOUNT WHEN '-1' THEN '1=1' ELSE 'ACCOUNT = '''
                    +CAST(@ACCOUNT AS varchar(50)) END+') '
select @Sql

------解决方案--------------------
declare @Sql varchar(1000)
declare @ACCOUNT varchar(50)='-1' --@ACCOUNT 为 testName 时也需要符合
Set @Sql ='select * from T_ORDER where ('+CASE @ACCOUNT WHEN '-1' THEN ' 1=1 ' ELSE ' ACCOUNT = '''+CAST(@ACCOUNT AS varchar(50))+'''' END +')' 
select @Sql