读书人

求高手修改一个存储过程,该如何解决

发布时间: 2012-02-10 21:27:42 作者: rapoo

求高手修改一个存储过程
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

读书人网 >SQL Server

热点推荐