用存储过程创建表,表名是存储过程的输入参数,出现问题!(50分)

  • 主题发起人 主题发起人 暖人心间
  • 开始时间 开始时间

暖人心间

Unregistered / Unconfirmed
GUEST, unregistred user!
下面是我写的存储过程,在执行时,创建的表名字不是输入的参数如‘001’
反而是“user_id”,在局部变量和字符串的转换中有错误,请各位释疑!

CREATE PROCEDURE CreateTemReport
@user_id varchar(80) --用户id号作为输入参数,并以它作为创建表的表名
AS
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[@user_id]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[@user_id];---判断是否已经存在以次为表名的表,若存在则删除
CREATE TABLE [dbo].[@user_id] (
[n_id] [int] IDENTITY (1, 1) NOT NULL ,
[papersize] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_no] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_code] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_count] [int] NULL ,
[total_count] [int] NULL ,
[mate_memo] [text] COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
 
先拼好字串,后Exec(字串)
 
........
DECLARE @sqlstr varchar(8000)
select @sqlstr=' CREATE TABLE [dbo].['+@user_id+'] (
[n_id] [int] IDENTITY (1, 1) NOT NULL ,
[papersize] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_no] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_code] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_count] [int] NULL ,
[total_count] [int] NULL ,
[mate_memo] [text] COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] '
exec(@sqlstr)
 
整理后的,成功!谢谢
CREATE PROCEDURE CreateTemReport
@user_id varchar(80)
as
DECLARE @sqlstr varchar(8000)
select @sqlstr=' CREATE TABLE [dbo].['+@user_id+'] (
[n_id] [int] IDENTITY (1, 1) NOT NULL ,
[papersize] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_no] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_code] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[mate_count] [int] NULL ,
[total_count] [int] NULL ,
[mate_memo] [text] COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] ';
exec(@sqlstr)

---------
 
后退
顶部