在SQL Server中动态修改数据表结构
版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://foresun.blog.51cto.com/221037/44182 |
因为需要编写一个统计字段和统计内容都不确定的报表,需要对报表结构进行动态验证,根据业务需要调整报表的数据结构,我通过一下的存储过程来实现的。以下代码在SQL Server 2000 + SP4中调试通过。
if exists(select * from sysobjects where lower(name)=lower('up_AddCol4Obbr') and xtype='P')
drop procedure up_AddCol4Obbr go create procedure up_AddCol4Obbr
@strTable nvarchar(100), @strColName nvarchar(100), @strType nvarchar(100) as begin declare @strSQL nvarchar(1000) if not exists(select * from syscolumns where lower(name)=lower(@strColName) and id in (select id from sysobjects where lower(name)=lower(@strTable) ))
begin select @strSQL = N'alter table ' + @strTable + ' add ' + @strColName + ' ' + @strType exec sp_executesql @strSQL
end else begin select @strSQL = N'alter table ' + @strTable + ' alter column ' + @strColName + ' ' + @strType exec sp_executesql @strSQL
end end go if exists(select * from sysobjects where lower(name)=lower('up_CheckCols4Obbr') and xtype='P')
drop procedure up_CheckCols4Obbr go create procedure up_CheckCols4Obbr
as begin declare @nColCnts smallint, @nShopCnts smallint, @nCol smallint, @nShop smallint declare @strColName nvarchar(30), @strType nvarchar(50), @strTable nvarchar(50) select @nColCnts = count(*) from u_obbc
select @nShopCnts = count(*) from u_obbs select @nCol=1, @nShop=1, @strTable='U_OBBR' while @nCol<=@nColCnts
begin select @strColName = 'TC' + right('00'+cast(@nCol as nvarchar(10)),2) select @strType = dType from joyouext.dbo.u_obbc where colId = @nCol exec up_AddCol4Obbr @strTable, @strColName, @strType
select @nCol = @nCol + 1
end while @nShop<=@nShopCnts
begin set @nCol=1 while @nCol<=@nColCnts begin select @strColName = 'BC' + right('00'+cast(@nShop as nvarchar(10)),2) + right('00'+cast(@nCol as nvarchar(10)),2) select @strType = dType from joyouext.dbo.u_obbc where colId = @nCol exec up_AddCol4Obbr @strTable, @strColName, @strType select @nCol = @nCol + 1 end select @nShop = @nShop + 1 end end go 本文出自 “富盛软件工作室” 博客,请务必保留此出处http://foresun.blog.51cto.com/221037/44182 本文出自 51CTO.COM技术博客 |



foresun
博客统计信息
热门文章
最新评论
友情链接