添加动态列的存储过程怎么写才对
我问题的想法是把表t1中的所有tname 列读出来 添加到t2表变为行名
create table t1
(tid int primary key,tname char(20)
)
create table t2
(tid int primary key
)
insert into t1 values(1,'一')
insert into t1 values(2,'二')
insert into t1 values(3,'三')
insert into t1 values(4,'四')
insert into t1 values(5,'五')
create procedure col
(
@i int out
)
as
declare @count int
declare @while int
declare @var varchar(20)
select @count = count(*) from t1
select @while = 1
while @while < @count
begin
select @var = (select tname from t1 where tid = cast(@while as varchar(20)))
alter table t2 add @var varchar(30) /*此处出错*/
set @while = @while + 1
end
select @i = @@error
还有别的方法吗?
问题点数:30、回复次数:4Top
1 楼happyflystone(无枪的狙击手)回复于 2006-03-01 19:10:57 得分 30
set nocount on
create table t1
(tid int primary key,tname char(20)
)
create table t2
(tid int primary key
)
insert into t1 values(1,'一')
insert into t1 values(2,'二')
insert into t1 values(3,'三')
insert into t1 values(4,'四')
insert into t1 values(5,'五')
---方法一,也就是你的方法
declare @count int
declare @while int
declare @var varchar(20)
select @count = count(*) from t1
select @while = 1
while @while <= @count
begin
select @var = (select tname from t1 where tid = cast(@while as varchar(20)))
exec('alter table t2 add '+@var + ' varchar(30)') /*此处出错*/
set @while = @while + 1
end
select * from t2
/*
tid 一 二 三 四 五
----------- ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------
*/
----方法二:
drop table t2
declare @s varchar(8000)
set @s = ''
select @s=@s+',['+rtrim(tname)+']=0' from t1
exec('select tid '+@s +' into t2 from t1 where 1 =2')
select * from t2
/*
tid 一 二 三 四 五
----------- ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------
*/
drop table t1,t2Top
2 楼happyflystone(无枪的狙击手)回复于 2006-03-01 19:14:53 得分 0
过程你自己搞定吧!!!Top
3 楼treeClimber(我以我血荐轩辕)回复于 2006-03-02 14:23:11 得分 0
exec() 字符串+变量形式Top
4 楼zl1980(友情暂住)回复于 2006-05-01 00:37:35 得分 0
-*upTop




