如果存在声明的变量DB,如何删除它?

时间:2016-02-04 11:49:04

标签: sql sql-server

我正在尝试删除声明变量数据库名称(如果它已经存在)。我有以下内容,但继续得到语法错误。 '@DB_NAME'附近的语法不正确。

USE MASTER  
GO


DECLARE @DB_NAME AS VARCHAR(50) 
SET @DB_NAME = 'TEST' 
DECLARE @DB_PATH AS VARCHAR(200) 
SET @DB_PATH = N'C:\\Clients\\TEST PILOT\\F - Raw Data\\'


IF EXISTS(SELECT * FROM sys.sysdatabases where name=@DB_NAME) 
DROP @DB_NAME

CREATE DATABASE @DB_NAME  
ON 
       (NAME = N'@DB_NAME', 
    FILENAME = N'C:\\Clients\\TEST PILOT\\F - Raw Data\\TEST.mdf', 
    SIZE = 1GB , 
    MAXSIZE = UNLIMITED, 
    FILEGROWTH = 1GB
    )

LOG ON
    (NAME = N'TEST_log', 
     FILENAME = N'C:\\Clients\\TEST PILOT\\F - Raw Data\\TEST.ldf', 
     SIZE = 2024KB , 
     MAXSIZE = 2GB , 
     FILEGROWTH = 10%
    )
GO 

1 个答案:

答案 0 :(得分:0)

您无法为数据库创建变量类型;

如果我没错,你想通过变量

中的输入删除数据库

你可以使用一些动态的sql来做同样的事情 这不是确切的脚本,您可以调整动态sql并获得所需的结果

USE MASTER
GO

DECLARE @DB_NAME AS VARCHAR(50),@ex_sql varchar(max)
SET @DB_NAME = 'TEST'
DECLARE @DB_PATH AS VARCHAR(200)
SET @DB_PATH = 'C:\Clients\TEST PILOT\F - Raw Data\'

IF EXISTS(SELECT * FROM sys.sysdatabases where name=@DB_NAME)
begin
set @ex_sql='drop database '+@DB_NAME
exec @ex_sql
end 
set @ex_sql=''
set @ex_sql='CREATE DATABASE '+@DB_NAME+
' ON 
(NAME = '''+@DB_NAME+''', 
    FILENAME = ''C:\Clients\TEST PILOT\F - Raw Data\TEST.mdf'', 
    SIZE = 1GB , 
    MAXSIZE = UNLIMITED, 
    FILEGROWTH = 1GB
    )

LOG ON
    (NAME = ''TEST_log'', 
     FILENAME = ''C:\Clients\TEST PILOT\F - Raw Data\TEST.ldf'', 
     SIZE = 2024KB , 
     MAXSIZE = 2GB , 
     FILEGROWTH = 10%
    )
GO'
exec @ex_sql