如何从命令行使用SQL Server参数输入?

时间:2014-07-12 01:24:51

标签: sql-server tsql command-line sql-server-2012

我是一个SQL新手,我正在试图弄清楚如何使用带有SQL Thru命令行的参数

对于我的老板/员工,我编写了批处理文件来运行SQL代码,以便导出数据等。在Access中我只需要[Paramerter],它会提示输入数据。

@State变量我希望能够动态设置。我希望批处理文件要求State和Query使用该信息。我不知道该怎么做。

批处理文件

sqlcmd -E -S ServerName -i C:\Lead$\SQL\MakeSTPhoeLists.sql
pause

SQL文件

Use LeadsDb
Go

Declare @State VarChar(2)
Set @State = 'DE'
DELETE FROM tblzExportPhone

INSERT INTO tblzExportPhone ( Phone )
SELECT tblLeads.Phone
FROM tblLeads
WHERE tblLeads.ST = @State

Declare @FileName VarChar(100)
Set @FileName = 'H:\Leads\Storage\STLists\' +  @State +'StatePhoneList.csv'

DECLARE @bcp_cmd4 VARCHAR(400) = ' BCP.EXE LeadsDb..tblzExportPhone out ' 
SET @bcp_cmd4 = @bcp_cmd4 + 'H:\Leads\SQL\Formats\PhoneTmp.csv' + ' -T -f H:\Leads\SQL\Formats\tblzExportPhone.fmt' 
SET @bcp_cmd4 = @bcp_cmd4 + ' & Copy /b     H:\Leads\SQL\Formats\ExPhone.csv+H:\Leads\SQL\Formats\PhoneTmp.csv ' + @FileName + ' /y'
Set @bcp_cmd4 = @bcp_cmd4 + ' & Del H:\Leads\SQL\Formats\PhoneTmp.csv'

谢谢。

2 个答案:

答案 0 :(得分:1)

在您的sql文件中使用此表示法$(statename)

将此添加到命令文件-v statename = %1

并通过参数mycommanfile.cmd DE

执行它

另请阅读this以获取完整示例。

答案 1 :(得分:0)

基本上我发现的是你必须制作一个存储过程并调用一个查询来运行它。我要留下一个例子。 BTW SQL查询从表创建CSV文件使用bcp然后使用RAR Dos Command将其解压缩。

BTW存储过程被使用,因为我试图做的其他方式没有我失败,但一旦我添加它我是金色的。可以使用Dos提示的bat文件,但我正在为'半计算机智能人'设置bat文件

希望这有助于像我这样的新手^^

BAT文件(cmd提示符)

Echo phone numbers in the State to send to Paramount.
Echo Then after the file is made converts it to Zip.
Echo '
Set /p State=Enter Initials of the State? :
sqlcmd -E -S Titania -i H:\Lead$\SQL\STPhones.sql -v StateName=%State%

SQL命令#1

Use dbNameHere
go
Declare @State NVarChar(2)
EXECUTE [dbo].[STPhoneListB] @State=$(StateName)

SQLCommand#2

Use dbNameHere
Go
CREATE PROCEDURE [dbo].[STPhoneListB]
    @State NVarChar(2) = 'DE',
    @Folder VarChar(100) = 'H:\Lead$'
AS
BEGIN
    Declare @FileName VarChar(150)
    Set @FileName = @Folder + '\STPhones_'+ @State +'.csv'

    Declare @DosCMD VarChar(150) = 'Del ' + @Folder +'\STPhones'+ @State
           +'.Zip /q'
    EXEC master..xp_cmdshell @DosCMD 
    DECLARE @bcp_cmd4 VARCHAR(400)
    DELETE FROM tblzExportPhone

    INSERT INTO tblzExportPhone ( Phone )
    SELECT tblLeads.Phone
    FROM tblLeads
    WHERE tblLeads.ST = @State
    Set @bcp_cmd4 = 'BCP.EXE LeadsDb..tblzExportPhone out ' 
    SET @bcp_cmd4 = @bcp_cmd4 + 'H:\SQL\PhoneTmp.csv' +
           ' -T -f H:\SQL\tblzExportPhone.fmt' 
    SET @bcp_cmd4 = @bcp_cmd4 
           + ' & Copy /b H:\SQL\ExPhone.csv+H:\SQL\PhoneTmp.csv '
           + @FileName + ' /y'
    Set @bcp_cmd4 = @bcp_cmd4 + ' & Del H:\SQL\PhoneTmp.csv'
    EXEC master..xp_cmdshell @bcp_cmd4 
    Set @bcp_cmd4 = 'cd '+ @Folder + 
           ' & "C:\Program Files\WinRAR\rar.exe" m STPhones_'+ @State +'.Zip ' + 
           'STPhones_'+ @State +'.csv'

    EXEC master..xp_cmdshell @bcp_cmd4 
    DELETE FROM tblzExportPhone
END