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

必须声明标量变量@T
有以下代码在Ctrl+F5时老是提示‘必须声明标量变量@T’,麻烦帮看下到底是哪里错了
SQL code

declare @Sql nvarchar(500)
declare @SysOrderNo int
declare @ShortName varchar(30),@Spec varchar(30),@Spec1 varchar(30),@Spec2 varchar(30),@Spec3 varchar(30),@Spec4 varchar(30)
declare @DataBaseName varchar(30)
declare @T table (Row        int identity(1,1)    not null,
    ShortName varchar(30)        null,
    Spec    varchar(30)            null,
    Spec1    varchar(30)            null,
    Spec2    varchar(30)            null,
    Spec3    varchar(30)            null,
    Spec4    varchar(30)            null,
    primary key (Row)
)
Set @DataBaseName='FYData'
Set @SysOrderNo=5
Set @Sql='insert into @T Select ShortName,Spec,Spec1,Spec2,Spec3,Spec4 From '+@DataBaseName+'.dbo.ORDERDETAIL '+' Where SysOrderNo='+cast(@SysOrderNo as varchar(10))
exec sp_executesql @Sql,N'@ShortName varchar(30) output,@Spec varchar(30) output,@Spec1 varchar(30) output,@Spec2 varchar(30) output,@Spec3 varchar(30) output,@Spec4 varchar(30) output,@T table output',@ShortName output,@Spec output,@Spec1 output,@Spec2 output,@Spec3 output,@Spec4 output,@T output
Select * From @T



消息框里提示错出在exec那一句

------解决方案--------------------
try this,
SQL code

declare @Sql nvarchar(500)
declare @SysOrderNo int
declare @ShortName varchar(30),@Spec varchar(30),@Spec1 varchar(30),@Spec2 varchar(30),@Spec3 varchar(30),@Spec4 varchar(30)
declare @DataBaseName varchar(30)
declare @T table (Row        int identity(1,1)    not null,
    ShortName varchar(30)        null,
    Spec    varchar(30)            null,
    Spec1    varchar(30)            null,
    Spec2    varchar(30)            null,
    Spec3    varchar(30)            null,
    Spec4    varchar(30)            null,
    primary key (Row)
)
Set @DataBaseName='FYData'
Set @SysOrderNo=5
Set @Sql=N'Select ShortName,Spec,Spec1,Spec2,Spec3,Spec4 From ['+@DataBaseName+'].dbo.ORDERDETAIL Where SysOrderNo='''+cast(@SysOrderNo as varchar(10))+''' '

insert into @T exec sp_executesql @Sql

Select * From @T