您当前的位置: 百科371电脑/网络数据库 → 电脑/网络内容 退出登录 用户管理 用户注册
本类热门文章
相关文章
中原建材网
SQL操作,求教

减小字体 增大字体

问题:遇到一个SQL操作难题,急请赐教!问题是这样的,有两张表表A报关单号 申报日期 商品货号 商品编码 137362081 2007-11-2 01-02000096 85389000 137382842 2007-12-3 01-02000096 85389000137382835 2007-12-3 01-02000096 85389000107382841 2007-12-3 01-02000124 85812000表B料号 单位 数量 报关单号 柜号01-02000096 个 37781 其中表B的[料号]与表A的[商品货号]对应,现在问题是要根据[料号]在表A查询所有[报关单号]合并入表B的[报关单号],格式如:137362081/137382842/137382835,同时将相应的[商品编码]填入表B的[柜号]栏位中!请问这个SQL脚本该怎么写?急请赐教!  

--可以批量执行,以下代码全部执行可以看到效果,大家可以试试。楼主只用修改下就可以使用。
--准备数据===========================================
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TempTable]') AND type in (N'U'))
DROP TABLE [dbo].[TempTable]
go
declare @T_A table(报关单号 varchar(10),申报日期 datetime,商品货号 varchar(15),商品编码 varchar(10))
insert into @T_A
select '137362081', '2007-11-2', '01-02000096', '85389000' union all
select '137382842', '2007-12-3', '01-02000096', '85389000' union all
select '137382835', '2007-12-3' ,'01-02000096' ,'85389000' union all
select '107382841', '2007-12-3', '01-02000124', '85812000'

declare @T_B table(料号 varchar(15),单位 varchar(10),数量 int,报关单号 varchar(4000),柜号 varchar(10))
insert into @T_B
select '01-02000096','个',37781,'','85389000'
union all
select '01-02000124','个',24983,'','85812000'

select identity(int,1,1) as sortid ,商品货号 into temptable from @T_A group by 商品货号
--==========================================================
--处理过程==================================================
declare @minid int
declare @maxid int
select @maxid = max(sortid),@minid = min(sortid) from temptable
declare @strSql varchar(4000)
declare @resSql varchar(4000)
set @strSql = ''
while @minid <= @maxid
begin
select @strSql = @strSql + 报关单号+'/' from @T_A where 商品货号 = (select 商品货号 from temptable where sortid = @minid)
Set @resSql = @strSql
Set @strSql = ''
select @resSql = substring(@resSql,1,len(@resSql)-1)
update @T_B
set 报关单号 = @resSql
where 料号 = (select 商品货号 from temptable where sortid = @minid)
set @minid = @minid + 1
end

select * from @T_B
--==========================================================

如果你对遇到一个SQL操作难题,急请赐教!问题是这样的,有两张表表A报关单号 申报日期 商品货号 商品编码 137362081 2007-11-2 01-02000096 85389000 137382842 2007-12-3 01-02000096 85389000137382835 2007-12-3 01-02000096 85389000107382841 2007-12-3 01-02000124 85812000表B料号 单位 数量 报关单号 柜号01-02000096 个 37781 其中表B的[料号]与表A的[商品货号]对应,现在问题是要根据[料号]在表A查询所有[报关单号]合并入表B的[报关单号],格式如:137362081/137382842/137382835,同时将相应的[商品编码]填入表B的[柜号]栏位中!请问这个SQL脚本该怎么写?急请赐教!这个问题有好的意见或 建议,请留言
[] [返回上一页] [打 印]
电脑/网络评论 (评论内容只代表网友观点,与本站立场无关!)

用户名: 查看更多评论

分 值:100分 85分 70分 55分 40分 25分 10分 0分

内 容:

         (注“”为必填内容。) 验证码: 验证码,看不清楚?请点击刷新验证码

中原建材网 简单版 站长QQ:382546553