我需要创建一个数据库,但要从变量中获取名称和路径:
declare @Datapath nvarchar = serverproperty('InstanceDefaultDataPath');
declare @Database nvarchar = 'DatabaseName';
use master
go
if exists (select name from sys.databases where name = '@Database')
drop database [@Database]
go
create database [@Database]
on primary (
name = '@Database_Data'),
filename = concat(@Datapath, '@Database_Data.mdf'),
size = 200MB,
maxsize = 20GB,
filegrowth = 40MB
)
collate Latin1_General_CI_AI
go
但我在第一行收到错误:
Implicit conversion from data type sql_variant to nvarchar is not allowed. Use the CONVERT function to run this query.
我在concat函数上也出错了。
我想在我的查询中使用@Datapath和@Database。
我错过了什么?
更新1
declare @Datapath nvarchar(200) = cast(serverproperty('InstanceDefaultDataPath') as nvarchar(200));
declare @Database nvarchar(50) = 'DatabaseName';
use master
go
if exists (select name from sys.databases where name = '@Database')
drop database [@Database]
go
create database [@Database]
on primary (
name = '@Database',
filename = concat(@Datapath, '@Database_Data.mdf'),
size = 200MB,
maxsize = 20GB,
filegrowth = 40MB
)
collate Latin1_General_CI_AI
go
答案 0 :(得分:1)
你的T-SQL有两个错误:
@Datapath
和@Database
变量的大小替换
declare @YourVariable nvarchar = ...
通过
declare @YourVariable nvarchar(<YourSize>) = ...
serverproperty
会返回sql_variant
,因此如果您需要nvarchar
,则可以投放它。更改
serverproperty('InstanceDefaultDataPath');
要
cast(serverproperty('InstanceDefaultDataPath') as nvarchar(200));
结果如下:
declare @Datapath nvarchar(200) = cast(serverproperty('InstanceDefaultDataPath') as nvarchar(200));
declare @Database nvarchar(50) = 'DatabaseName';
如果需要,可随意调整nvarchar大小。