在SQL Server 2005的存储过程中动态创建表


在尝试做在线考试系统的过程中,为了管理每个学生的考试信息,就考虑为每个学生创建以学号命名的临时数据表。

  在存储过程中动态创建表如果不使用参数的话很好创建。方法如下:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->alter procedure [dbo].[ZXKS_GETSCORE] 
  AS 
  begin transaction 
  --创建临时表,直接命名 
  create table temp_tablename 
  ( 
  id int primary key, 
  da varchar(300), 
  fs int 
  ) 
  declare @count int 
  select @count=@@error 
  if(@count=0) 
  commit transaction 
  else 
  rollback transaction 
  如果要将传入参数作为数据表名的话,就会遇到一个问题:如果表名是数字那么SQL SERVER 2005认不出来,会提示错误。必须将数字的表名前加上非数字的字符。存储过程如下所示:


Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->/*  createtable ’123456’  */ 
alter procedure createtable 
  @xuehao varchar(20) 
  as 
  declare @tablename varchar(20) 
  set @tablename=’temp’+@xuehao 
  exec(’create Table ’+@tablename+’ 
  ( name nvarchar(15), 
  address nvarchar(50) 
  )’) 
  并且将参数作为数据表名的话,创建方法要使用exec方法,使用前面介绍的那个方法行不通


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3