declare @sql varchar(8000)
declare @temp1 int
select @temp1 = 1set @sql='select top '+cast(@temp1 as varchar(10))+' * from xxx'exec(@sql)

解决方案 »

  1.   

    declare @temp1 int
    select @temp1 = 1
    exec('select top  '+@temp1+' dateGuid from WorkingDay')
      

  2.   

    --楼上的不行.declare @temp1 int
    select @temp1 = 1
    declare @s varchar(8000)
    set @s='select top '+cast(@temp1 as varchar)+' dateGuid from WorkingDay '
    exec(@s)
      

  3.   

    declare @temp1 int
    select @temp1 = 1
    declare @s varchar(8000)
    set @s='select top '+convert(nvarchar(10),@temp1)+' dateGuid from WorkingDay '
    exec(@s)
      

  4.   

    这个是用在函数中的,整个语句是
    declare @temp1 int
    select @temp1 = 10
    select top 1  @tempdate = CONVERT(datetime, wdate)  from WorkingDay where  dateGuid not in  (select top ' + convert(nvarchar(50),@temp1) + ' dateGuid from WorkingDay where   ORDER BY CONVERT(datetime, wdate) ) and isWorkingday = 1 
    上面的语句需要返回一个字,我用了 exec sp_executesql  方法,但在程序调用此函数有错误,不能这么用的
      

  5.   

    上面写错了这个是用在SQL用户自定义函数中的,整个语句是
    declare @temp1 int
    select @temp1 = 10
    select top 1  @tempdate = CONVERT(datetime, wdate)  from WorkingDay where  dateGuid not in  (select top ' + convert(nvarchar(50),@temp1) + ' dateGuid from WorkingDay where   ORDER BY CONVERT(datetime, wdate) ) and isWorkingday = 1 
    上面的语句需要返回一个@tempdate ,我用了 exec sp_executesql  方法,但在程序调用此函数有错误,不能这么用的
      

  6.   

    declare @temp1 int,@sql varchar(1000)
    select @temp1 = 10
    set @sql='select top 1  @tempdate = CONVERT(datetime, wdate)  from WorkingDay where  dateGuid not in  (select top ' + convert(varchar(12),@temp1) + ' dateGuid from WorkingDay where   ORDER BY CONVERT(datetime, wdate) ) and isWorkingday = 1 '
    exec (@sql)