当前位置: 代码迷 >> Sql Server >> 存储过程未声明变量解决方法
  详细解决方案

存储过程未声明变量解决方法

热度:43   发布时间:2016-04-24 09:51:25.0
存储过程未声明变量
有A,B表,用id和unti关联ID(ID),UNTI(生产线),CUSTOMER (项目),DATE(日期),CODE(材料编码),USE(用量)
A表结构是                                B表结构是
ID   UNTI    CUSTOMER     DATE                    ID        UNTI        CODE      USE
1     1#            A                   2014-10-20            1          1#              A            100  
2     1#            A                   2014-10-21            1          1#              B            100       
1     2#            A                   2014-10-21            1          2#              A             100
                                                                           2         1#              B             100
我用行列转换后得到新表结构是
ID    UNTI    CUSTOMER         DATE               A       B
1      1#                   A           2014-10-20         100    100  
1      2#                   A           2014-10-21         100      0
2      1#                   A           2014-10-21         0     100  
我创建了个存储过程,但是提示未声明变量,帮忙看下应该怎么修改
creater proc export
@unti    nvarchar(50),
@customer  nvarchar(50),
@date    date
as
declare @1 varchar(8000)
set @1='select unti,customer,date'
select @1=@1+',sum(case code when'''+code+"""then use else 0 end)'['+code+']' from (select distinct code from B)c
set @1=@1+' from (select * from a where @unti=unti and @customer=customer and @date=date)a left join b on a.id=b.id and a.unti=b.unti'
set @1=@1+' group by unti,customer,date'
exec(@1)

------解决思路----------------------

create proc export
@unti    nvarchar(50),
@customer  nvarchar(50),
@date    date
as
declare @sql varchar(8000)
set @sql='select unti,customer,date'
select @sql=@sql+',sum(case code when '''+code+''' then use else 0 end)''['+code+']''' from (select distinct code from B)c
set @sql=@sql+' from (select * from a where unti='''+@unti+''' and customer='''+@customer+''' and date='+@date+')a left join b on a.id=b.id and a.unti=b.unti'
set @sql=@sql+' group by a.unti,a.customer,a.date'
exec(@sql)


------解决思路----------------------
你这个用的一团糟 啊。怎么会有双引号啊。还有变量应该分出来。不应该直接字符串里面啊。
  相关解决方案