如何将参数传递给使用 sqlcmd 调用的 SQL Server 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3814302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass in parameters to a SQL Server script called with sqlcmd?
提问by Jeremy
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:
是否可以将参数传递给 SQL Server 脚本?我有一个创建数据库的脚本。它是使用 sqlcmd 从批处理文件中调用的。该 SQL 脚本的一部分如下:
CREATE DATABASE [SAMPLE] ON PRIMARY
( NAME = N'SAMPLE', FILENAME = N'c:\dev\SAMPLE.mdf' , SIZE = 23552KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'SAMPLE_log', FILENAME = N'c:\dev\SAMPLE_log.ldf' , SIZE = 29504KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
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:\dev\SAMPLE.mdf' and 'C:\dev\SAMPLE_log.ldf'.
我希望能够传入数据库和日志的文件名,这样我就不必硬编码“C:\dev\SAMPLE.mdf”和“C:\dev\SAMPLE_log.ldf”。
Is there a way to do this? I am running Microsoft SQL Server 2008 Express. Let me know if you need any more information.
有没有办法做到这一点?我正在运行 Microsoft SQL Server 2008 Express。如果您需要更多信息,请告诉我。
回答by Joe Stefanelli
Use the -v switch to pass in variables.
使用 -v 开关传入变量。
sqlcmd -v varMDF="C:\dev\SAMPLE.mdf" varLDF="C:\dev\SAMPLE_log.ldf"
Then in your script file
然后在你的脚本文件中
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%)