create table subject
(
编号 int primary key ,
课程 varchar(10)
)
go
Insert subject Values(1,'English') --加入一列数据,以避免@sub为空
GO
declare @count int
declare @sub varchar(10)
set @count = 1
select @sub = 课程 from subject where( 编号 = @count)
EXEC ('create table table ('+@sub +' int)') --使用动态SQL语句
(
编号 int primary key ,
课程 varchar(10)
)
go
Insert subject Values(1,'English') --加入一列数据,以避免@sub为空
GO
declare @count int
declare @sub varchar(10)
set @count = 1
select @sub = 课程 from subject where( 编号 = @count)
EXEC ('create table table ('+@sub +' int)') --使用动态SQL语句
exec('string')
或
sp_executesql()
具體的用法可以查Transact-SQL Help
+cast(@id as nvarchar(30)) +'and thepicid not in
(select top '+cast(@thepage as nvarchar(30))+'
thepicid from pic where id='+cast(@id as nvarchar(30))+'
order by thepicid) order by thepicid'
exec sp_executesql @sql
create table subject --创建课程表
(
编号 int primary key ,
课程 varchar(10)
)
--输入课程名称
insert subject values(01,'vb')
insert subject values(02,'c')
insert subject values(03,'java')
insert subject values(04,'html')
insert subject values(05,'c++')
insert subject values(06,'asp')
create table table--创建成绩表
(
[No] int primary key
)declare @count int--定义编号的变量
declare @allcount int
declare @sub varchar(10)--定义课程变量
set @count
select @allcount = count(*) from subject--课程表的记录的数量
--把课程表的记录作为字段输入到成绩表中
while @count <= @allcount
begin
select @sub = 课程 from subject where( 编号 = @count)
set @count = @count +1
EXEC ('alter table table add '+ @sub + ' varchar (10) Null') --使用动态SQL语句
end
出错的原因是由于你的课程中有一门语言"C++"有两个"+"号,这里要处理一下。
修改好的语句如下:create table subject --创建课程表
(
编号 int primary key ,
课程 varchar(10)
)
--输入课程名称
insert subject values(01,'vb')
insert subject values(02,'c')
insert subject values(03,'java')
insert subject values(04,'html')
insert subject values(05,'c++')
insert subject values(06,'asp')
create table table--创建成绩表
(
[No] int primary key
)declare @count int--定义编号的变量
declare @allcount int
declare @sub varchar(10)--定义课程变量
--set @count
set @count =1 --这里改为set @count =1
select @allcount = count(*) from subject--课程表的记录的数量
--把课程表的记录作为字段输入到成绩表中
while @count <= @allcount
begin
select @sub = 课程 from subject where( 编号 = @count)
If CharIndex('+',@sub)>0 --这里加上这两句代码。
Set @sub='['+@sub+']'
set @count = @count +1
EXEC ('alter table table add '+ @sub + ' varchar (10) Null') --使用动态SQL语句
end