我在构造一个存储过程时候需要达到这么个目的:
找出性别为‘f’的前n个员工,所以我执行这么一句:
如果执行这句没有问题:
declare @n int,@sex char(1)
set @n=3
set @sex='f'
exec('select top '+@n +' * from employee ' )但是如果执行这句就显示有问题了:
declare @n int,@sex char(1)
set @n=3
set @sex='f'
exec('select top '+@n +' * from employee where sex='+@sex )
就有问题了:
服务器: 消息 207,级别 16,状态 3,行 1
列名 'f' 无效。
怎么让一个参数传递到等号后面?怎么才能达到这个效果?谢谢各位!

解决方案 »

  1.   

    declare   @n   int,@sex   char(1)
    set   @n=3
    set   @sex='f'
    --exec('select   top '+@n   +'   *   from   employee   where   sex='+@sex   )
    exec('select   top '+@n   +'   *   from   employee   where   sex='''+@sex+''''   )
      

  2.   

    选中 -> 插入源代码 -> 选代码类型
      

  3.   

    declare   @n   int,@sex   char(1) 
    set   @n=3 
    set   @sex= 'f ' 
    exec( 'select   top   '+@n   + '   *   from   employee   where   sex= '''+@sex  +'''' ) 
      

  4.   

    select * from tb where sex='f'当用exec执行时,这是个字串
    'select * from tb where sex='f''但是字串中嵌了字串,要予区分.
    将'  '定界的字串中出现的'用''来转义

    '  select * from tb where sex=''f''  '而你的@f是个变量
    ' select * from tb where sex=''' + @f + ''''
    先发上来再看,现在自己都不知道是什么颜色了.
      

  5.   

    第1个单引和第4个单引是成对的,
      用来定界 select * from tb where sex=''
    第2个和第3个其实是一个, 就是'转义成的两个第5个和第8个是成对的 用来定界 ''
    第6和第7是其实也是一个,就是'转义成的两个2,3在前,6,7在后,来定界@f的值
    即 ''f''
    实际上表示的是 'f'
      

  6.   

    懒得写了,这里有个链接,昨晚刚回答了一位朋友:http://topic.csdn.net/u/20071106/11/019d01f2-e826-4714-8494-f403e3d23153.html
      

  7.   

    执行前最好用print()将要运行的动态语句打印出来查看是否有错误。