求助sql语句,我希望将IN语句的结果存入一个变量@bResult,但set @bResult = 1 IN(1,2,3)是无法执行的,请问有什么方法可以解决吗?

解决方案 »

  1.   

    刚才那位兄弟麻烦给下解答好吗?如何用字符串?如何用动态SQL?
    如果是Select * from table where 1 IN(1,2,3),执行是完全没问题的,但我只想得到1 IN(1,2,3)这个表达式的值,该如何做呢
      

  2.   

    楼主是否是要这样?
    set @bResult = 'Select * from table where 1 IN(1,2,3)'
    exec(@bResult)
      

  3.   

    我写的很清楚是希望实现set @bResult = 1 IN(1,2,3)的效果,但这种语句是无法执行的,我不需要记录集,只需要一个IN表达式的bool值,其中的1和(1,2,3)到时候都要用变量来替换的
      

  4.   

    自己解决了:
    declare @bResult bit
    Set @bResult = 0
    Select @bResult = 1 Where 1 in (1,2,3)鄙视2楼的,只会说轻巧的话,讲到实际了却跑的不知道哪去了
      

  5.   


    动态sql语句基本语法 
    1 :普通SQL语句可以用Exec执行 eg:   Select * from tableName 
             Exec('select * from tableName') 
             Exec sp_executesql N'select * from tableName'    -- 请注意字符串前一定要加N 2:字段名,表名,数据库名之类作为变量时,必须用动态SQL eg:   
    declare @fname varchar(20) 
    set @fname = 'FiledName' 
    Select @fname from tableName              -- 错误,不会提示错误,但结果为固定值FiledName,并非所要。 
    Exec('select ' + @fname + ' from tableName')     -- 请注意 加号前后的 单引号的边上加空格 当然将字符串改成变量的形式也可 
    declare @fname varchar(20) 
    set @fname = 'FiledName' --设置字段名 declare @s varchar(1000) 
    set @s = 'select ' + @fname + ' from tableName' 
    Exec(@s)                -- 成功 
    exec sp_executesql @s   -- 此句会报错 declare @s Nvarchar(1000)  -- 注意此处改为nvarchar(1000) 
    set @s = 'select ' + @fname + ' from tableName' 
    Exec(@s)                -- 成功     
    exec sp_executesql @s   -- 此句正确 3. 输出参数 
    declare @num int, 
            @sqls nvarchar(4000) 
    set @sqls='select count(*) from tableName' 
    exec(@sqls) 
    --如何将exec执行结果放入变量中? declare @num int, 
                   @sqls nvarchar(4000) 
    set @sqls='select @a=count(*) from tableName ' 
    exec sp_executesql @sqls,N'@a int output',@num output 
    select @num 
      

  6.   

    所谓的动态SQL我知道的,但我现在要解决的问题没有涉及到动态SQL,只是一个取值的问题
      

  7.   

    set @aaa = case when 1 in (1,2) then 'a' else 'b' end
      

  8.   

    谢谢楼上的小虫,现在简单的表达式可以实现了,但问题是1 in (1,2)这句式子要通过拼字符串来获得的,不知道你有什么好办法可以实现呢?解决后另外开帖100分奉送
    具体问题请看这里http://community.csdn.net/Expert/TopicView.asp?id=5431251
      

  9.   

    改用CharIndex做判斷,不使用In做判斷。
    declare @bResult bit
    Set @bResult = 0
    Select @bResult = 1 Where CharIndex(',' + Cast(1 As Varchar) + ',' , ',' + '1,2,3' + ',') > 0
      

  10.   

    在前後加上","是為了防止將11這樣包含1的數據查出。
    或者使用Likedeclare @bResult bit
    Set @bResult = 0
    Select @bResult = 1 Where  ',' + '1,2,3' + ',' Like '%,' + Cast(1 As Varchar) + ',%'
    Select @bResult