日期:2014-05-18 浏览次数:20667 次
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: xujinli -- Create date: 2011-12-7 -- Description: 创建数据库和表 -- ============================================= create procedure P_Create --@year nvarchar(100)//这样的写法是传进来的参数 AS declare @year nvarchar(100), @KuName nvarchar(200) BEGIN select @year=cast(YEAR(getdate()) as nvarchar), @KuName='XQ_'+Cast(YEAR(getdate()) as nvarchar(50)) if exists(select * from sys.databases where [name]=@KuName ) --判断该数据是否存在 print '该数据库已经存在' else begin declare @sql varchar(5000) select @sql='create database '+@KuName+' ON PRIMARY ' +'(name='''+@KuName+''',filename=''D:\Project\DataBase\'+@KuName+'.mdf'', ' +'size=20,filegrowth=10%) log on(name='''+@KuName+'_log'',' +'filename=''D:\Project\DataBase\'+@KuName+'.ldf'',size=20,filegrowth=10%)' exec(@sql) end END go
------解决方案--------------------
不行,一定要用动态SQL,举个最简单的例子,
-- 建测试库,正常. create database abcd -- 删除测试库,正常. drop database abcd -- 用变量做库名,出错. declare @KuName nvarchar(50) select @KuName='abcd' create database @KuName Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '@KuName'.
------解决方案--------------------
要用动态语句创建库表
------解决方案--------------------
-- 在存储过程中,建完数据库后执行. exec('use '+@KuName+' create table [表名]([字段名] [数据类型]...)')
------解决方案--------------------
不需要"go", 删除即可.
请看10楼代码.