如何将参数传递给使用 sqlcmd 调用的 SQL Server 脚本?

2021-12-29 00:00:00 sql parameters scripting sql-server sqlcmd

是否可以将参数传递给 SQL Server 脚本?我有一个创建数据库的脚本.它是使用 sqlcmd 从批处理文件中调用的.该 SQL 脚本的一部分如下:

Is it possible to pass parameters to a SQL Server script? I have a script that creates a database. It is called from a batch file using sqlcmd. Part of that SQL script is as follows:

CREATE DATABASE [SAMPLE] ON  PRIMARY 
( NAME = N'SAMPLE', FILENAME = N'c:devSAMPLE.mdf' , SIZE = 23552KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'SAMPLE_log', FILENAME = N'c:devSAMPLE_log.ldf' , SIZE = 29504KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)

我希望能够传入数据库和日志的文件名,这样我就不必硬编码C:devSAMPLE.mdf"和C:devSAMPLE_log.ldf".

I want to be able to pass in the filenames for the database and the log so that I don't have to hardcode 'C:devSAMPLE.mdf' and 'C:devSAMPLE_log.ldf'.

有没有办法做到这一点?我正在运行 Microsoft SQL Server 2008 Express.如果您需要更多信息,请告诉我.

Is there a way to do this? I am running Microsoft SQL Server 2008 Express. Let me know if you need any more information.

推荐答案

使用 -v 开关传入变量.

Use the -v switch to pass in variables.

sqlcmd -v varMDF="C:devSAMPLE.mdf" varLDF="C:devSAMPLE_log.ldf"

然后在你的脚本文件中

CREATE DATABASE [SAMPLE] ON  PRIMARY 
( NAME = N'SAMPLE', FILENAME = N'$(varMDF)' , SIZE = 23552KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
 LOG ON 
( NAME = N'SAMPLE_log', FILENAME = N'$(varLDF)' , SIZE = 29504KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)

相关文章