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

求高手修改一个存储过程
CREATE   proc   xxxx
(
@companyname   int=null--这里不知道要如何改,改成什么类型的
)
as
begin

select   公司id,gsid,公司名称,sum(金额)   as   用款总额   from  
(
                                      select   *   from   a
                                      union   all
                                      select   *   from   b
)   t  
where   审批意见= '同意 '
and   gsid   in   (case   when   @companyname   is   null   then   gsid   else   @companyname   end)
group   by   公司id,gsid,公司名称   order   by   公司id

end
GO

我想实现@companyname这个输入参数可以直接支持如这样的123,56,554(数量不定,数值是gsid字段值)或是123这样单个gsid,现在不行,会报错,不知道要如何改了
@companyname   如果改成varchar   也不行,提示:

将   varchar   值   '350,657 '   转换为数据类型为   int   的列时发生语法错误。

这样的错误,
INT类型时会根本不让输入

------解决方案--------------------
--try

CREATE proc xxxx
(
@companyname varchar(200)=null--这里不知道要如何改,改成什么类型的
)
as
begin

declare @sql varchar(8000)
set @sql= '
select 公司id,gsid,公司名称,sum(金额) as 用款总额 from
(
select * from a
union all
select * from b
) t
where 审批意见= ' '同意 ' '
'
if @companyname is not null
set @sql=@sql+ ' and gsid in( '+@companyname+ ') '

set @sql=@sql+ '
group by 公司id,gsid,公司名称
order by 公司id
'

exec(@sql)
end
GO
------解决方案--------------------
CREATE proc xxxx
(
@companyname nvarchar(1000)= ' '--这里不知道要如何改,改成什么类型的
)
as
begin

select 公司id,gsid,公司名称,sum(金额) as 用款总额 from
(
select * from a
union all
select * from b
) t
where 审批意见= '同意 '
and ', 'cast(gsid as nvarchar(16))+ ', ' in (case when @companyname = ' ' then ', 'cast(gsid as nvarchar(16))+ ', ' else ', '+@companyname+ ', ' end)
group by 公司id,gsid,公司名称 order by 公司id

end
GO