如何在 SQLCMD 中抑制连字符

发布于 2024-08-24 01:06:25 字数 641 浏览 8 评论 0原文

如何在此 sqlcmd 命令的结果集中隐藏连字符 (------------):

C:\temp>sqlcmd -d AdventureWorks -s ";" 
 -Q "SET NOCOUNT ON SELECT top 5 FirstName, LastName FROM Person.Contact;"
FirstName                                         ;LastName
--------------------------------------------------;----------------------------
Gustavo                                           ;Achong
Catherine                                         ;Abel
Kim                                               ;Abercrombie
Humberto                                          ;Acevedo
Pilar                                             ;Ackerman

C:\temp>

How can I suppress hyphens (------------) from the results set of this sqlcmd command:

C:\temp>sqlcmd -d AdventureWorks -s ";" 
 -Q "SET NOCOUNT ON SELECT top 5 FirstName, LastName FROM Person.Contact;"
FirstName                                         ;LastName
--------------------------------------------------;----------------------------
Gustavo                                           ;Achong
Catherine                                         ;Abel
Kim                                               ;Abercrombie
Humberto                                          ;Acevedo
Pilar                                             ;Ackerman

C:\temp>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

浮世清欢 2024-08-31 01:06:26

从结果中删除破折号:

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'testMail',
@recipients = '[email protected]',
@query = '  
SET NOCOUNT ON
SELECT W.* FROM (
(SELECT CAST("id" AS VARCHAR(5) ) as id , CAST("name" AS VARCHAR(50) )as name ) 
UNION ALL 

SELECT CAST( id AS VARCHAR(5) ) AS id, CAST (name AS VARCHAR(50) ) AS name from mydb.dbo.bank
 )W
' ,
@subject = 'Test email',
@attach_query_result_as_file = 1,
@query_attachment_filename='filename.xls',
@query_result_separator='   ',   
@query_result_header = 0

    -----remember @query..separator should be--Tab space----

remove dashes from results:

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'testMail',
@recipients = '[email protected]',
@query = '  
SET NOCOUNT ON
SELECT W.* FROM (
(SELECT CAST("id" AS VARCHAR(5) ) as id , CAST("name" AS VARCHAR(50) )as name ) 
UNION ALL 

SELECT CAST( id AS VARCHAR(5) ) AS id, CAST (name AS VARCHAR(50) ) AS name from mydb.dbo.bank
 )W
' ,
@subject = 'Test email',
@attach_query_result_as_file = 1,
@query_attachment_filename='filename.xls',
@query_result_separator='   ',   
@query_result_header = 0

    -----remember @query..separator should be--Tab space----
离旧人 2024-08-31 01:06:26

我通常按​​如下方式处理生成的 .csv 文件:

sed -i '2d' "$file"  # remove 2nd line of dashes
sed -i '$d' "$file"  # remove last line (row count string)
sed -i '$d' "$file"  # remove one more empty line at the end of the file

其中:

  • -i 就地编辑文件...
  • 2d 删除第 2 行,在这种情况下,破折号线...
  • $d 删除文件末尾的单行...
  • "$file" 是保存路径的 bash 变量字符串到 .csv 文件。

I typically process the resulting .csv file as follows:

sed -i '2d' "$file"  # remove 2nd line of dashes
sed -i '$d' "$file"  # remove last line (row count string)
sed -i '$d' "$file"  # remove one more empty line at the end of the file

Where:

  • -i edits the file in-place...
  • 2d deletes line 2, in this case, the lines of dashes...
  • $d deletes single line at the end of the file...
  • "$file" is the bash variable holding the path string to the .csv file.
自由范儿 2024-08-31 01:06:26

这就是我最终得到的结果并且对我来说效果很好:

sqlcmd -S 12.34.56.789 -i "C:\Qry.sql" -s"," -W -w1000 | findstr /V /R /C:"^[-,]*$" > Reprt.csv

我相信在这一点上,findstr &正则表达式是所有需要解释的内容:

findstr /V /R /C:"^[-,]*$"

正则表达式指出“在开始 ^ 时,有 - 或 , [-,] 任意次数 *< /code>,直到到达行尾 $

是,显示任何不匹配的内容。

意思 > 随后将显示重定向到一个文件,

我也将其添加到我的 SQL 文件中:

SET NOCOUNT ON;

This is what I ended up with and works well for me:

sqlcmd -S 12.34.56.789 -i "C:\Qry.sql" -s"," -W -w1000 | findstr /V /R /C:"^[-,]*$" > Reprt.csv

I believe at this point, the findstr & regex are all that needs to be explained:

findstr /V /R /C:"^[-,]*$"

The regex states "At the beginning ^, has either - or , [-,] any number of times *, until you reach the end of the line $.

/V means, show me anything that doesn't match.

The > following it redirects the display to a file.

I did also add this to my SQL file:

SET NOCOUNT ON;
泪眸﹌ 2024-08-31 01:06:26

以下行:

findstr /R /C:"^[^-]*$" MyTableColumns.csv > MyTableHeader.csv

非常危险,因为它删除了所有包含“-”的行。
你最好看看 findstr /?并使用类似的东西:

findstr /B /V /C:"-----" MyTableColumns.csv > MyTableHeader.csv

The following line:

findstr /R /C:"^[^-]*$" MyTableColumns.csv > MyTableHeader.csv

is very dangerous as it removes all lines containing a "-".
You better have a look at findstr /? and use something like:

findstr /B /V /C:"-----" MyTableColumns.csv > MyTableHeader.csv
少年亿悲伤 2024-08-31 01:06:26

如果您想将数据假脱机输出,则可以设置以下开关:

SET UNDERLINE OFF;

if you want to spool the data out then you can set the following switch:

SET UNDERLINE OFF;

巷雨优美回忆 2024-08-31 01:06:26

我认为没有任何选项可以实现这一目标 - 恐怕您将不得不忍受这些标头。

I don't think there's any option available to achieve this - you'll have to live with those headers, I'm afraid.

笔芯 2024-08-31 01:06:25

使用 -h -1 选项从输出中删除列标题和破折号 (--------),并使用 SET NOCOUNT ON 删除“受影响的行”在最后。如果您要创建报告或 CSV 文件以供另一个系统处理,这非常有用。

示例:

SQLCMD -S 127.0.0.1\SQL_SERVER_Instance -d db_name -U db_login -P password -i your_script.sql -o your_output.csv -h -1

在您的 SQL 脚本中:

SET NOCOUNT ON -- removes (rows affected from the output)
select 'your_column_1, your_column_2'
select * from your_table

您不需要为此在 select 语句之间使用并集。

Use the -h -1 option to remove the column headers and the dashes (--------) from the output and SET NOCOUNT ON to remove the "rows affected" at the end. This is great if you're creating a report or CSV file for another system to process.

Example:

SQLCMD -S 127.0.0.1\SQL_SERVER_Instance -d db_name -U db_login -P password -i your_script.sql -o your_output.csv -h -1

In your SQL script:

SET NOCOUNT ON -- removes (rows affected from the output)
select 'your_column_1, your_column_2'
select * from your_table

You don't need to use a union between your select statements for this.

幸福不弃 2024-08-31 01:06:25

我唯一能想到的是使用 -h -1 开关删除标题,并将列名添加为 SQL 查询的第一行:

SELECT 'FirstName' as FirstName, 'LastName' as LastName
UNION
SELECT top 5 FirstName, LastName FROM Person.Contact

请注意,如果还有其他数据类型,则 (var)char,您需要使用以下方式转换字段:CAST(MyColumnName AS varchar(32)) as MyColumnName

The only thing I can think of is removing the header using the -h -1 switch and adding the column names as the first row to the SQL Query:

SELECT 'FirstName' as FirstName, 'LastName' as LastName
UNION
SELECT top 5 FirstName, LastName FROM Person.Contact

Note that if there are other data types then (var)char, you need to convert the field using : CAST(MyColumnName AS varchar(32)) as MyColumnName

感性 2024-08-31 01:06:25

如何在此 sqlcmd 命令的结果集中隐藏连字符 (------------):

您可以在一个命令中以简单的方式完成这一切,无需任何脚本或文件操作!

sqlcmd -d AdventureWorks -s ";" -Q "SET NOCOUNT ON; SELECT top 5 FirstName, LastName FROM Person.Contact" |findstr /v /c:"---"

添加 set nocount on; 以删除 (X rows受影响) 行。
添加 |findstr /v /c:"---" 以删除下划线。
这样你就可以得到一个干净的答案,只有:

FirstName                                         ;LastName
Gustavo                                           ;Achong
Catherine                                         ;Abel
Kim                                               ;Abercrombie
Humberto                                          ;Acevedo
Pilar                                             ;Ackerman

How can I supress hyphens (------------) from the results set of this sqlcmd command:

You can do it all in a simple way in one command, without any script or file manipulation!

sqlcmd -d AdventureWorks -s ";" -Q "SET NOCOUNT ON; SELECT top 5 FirstName, LastName FROM Person.Contact" |findstr /v /c:"---"

Add set nocount on; to remove the (X rows affected) line.
Add |findstr /v /c:"---" to remove the underlines.
This way you get a clean answer, with only:

FirstName                                         ;LastName
Gustavo                                           ;Achong
Catherine                                         ;Abel
Kim                                               ;Abercrombie
Humberto                                          ;Acevedo
Pilar                                             ;Ackerman
巷子口的你 2024-08-31 01:06:25

仅使用 sqlcmd 和 Windows 命令行,不使用存储过程:

REM Get the column headers ("set nocount on" is necessary to suppress the rows affected message)
sqlcmd -S MyServer -Q "set nocount on;select top 0 * from MyDatabase.MySchema.MyTable" -o "MyTableColumns.csv" -s "," -W

REM Remove hyphen line
findstr /R /C:"^[^-]*$" MyTableColumns.csv > MyTableHeader.csv

REM Get data without headers
sqlcmd -S MyServer -Q "set nocount on;select * from MyDatabase.MySchema.MyTable" -o "MyTableData.csv" -h -1 -s "," -W
REM You can also use bcp for this step
REM bcp "select * from MyDatabase.MySchema.MyTable" queryout  "MyTableData.csv"  -c -t"," -r"\n" -S MyServer -T

REM Append header and data
type MyTableHeader.csv MyTableData.csv > MyTableDataWithHeader.csv

要处理内部带有分隔符的数据(例如“Atlanta, GA”),您需要单独指定字段(而不是使用“select *”)并使用SQL Server 中的 QUOTENAME 函数。

Using only sqlcmd and the Windows command line, with no stored procedures:

REM Get the column headers ("set nocount on" is necessary to suppress the rows affected message)
sqlcmd -S MyServer -Q "set nocount on;select top 0 * from MyDatabase.MySchema.MyTable" -o "MyTableColumns.csv" -s "," -W

REM Remove hyphen line
findstr /R /C:"^[^-]*$" MyTableColumns.csv > MyTableHeader.csv

REM Get data without headers
sqlcmd -S MyServer -Q "set nocount on;select * from MyDatabase.MySchema.MyTable" -o "MyTableData.csv" -h -1 -s "," -W
REM You can also use bcp for this step
REM bcp "select * from MyDatabase.MySchema.MyTable" queryout  "MyTableData.csv"  -c -t"," -r"\n" -S MyServer -T

REM Append header and data
type MyTableHeader.csv MyTableData.csv > MyTableDataWithHeader.csv

To handle data with delimiters inside (for example "Atlanta, GA") you'll need to specify the fields separately (rather than use "select *") and use the QUOTENAME function in SQL Server.

上课铃就是安魂曲 2024-08-31 01:06:25

或者也许通过 sed as: 后处理输出

sqlcmd ... | sed -e '2d'

以删除第二行?

您可以从 http://gnuwin32.sourceforge.net/packages/sed.htm< 获取 Win32 sed< /a>

Or maybe post-process the output through sed as:

sqlcmd ... | sed -e '2d'

to delete the second line?

You can get a Win32 sed from http://gnuwin32.sourceforge.net/packages/sed.htm

属性 2024-08-31 01:06:25

为了去掉连字符,我在存储过程中添加了一些代码,这些代码将仅输出列标题。使用 SQLCMD 提取数据分为两部分。

首先,我使用一组特殊的参数调用存储过程。就我而言,当我使用所有 NULL 调用 SP 时,这意味着我希望拥有列标题。

然后我再次调用 SQLCMD 并将输出附加到我之前刚刚创建的文件中,瞧!

创建一个空白 CSV 文件来保存列标题

sqlcmd -S server -d database -U username -P password -o "somefile.csv" -h-1 
  -Q "exec myStoredProcedure NULL, NULL" -W -w 2000 -s"," > sometextfile.csv

现在附加存储过程的输出结果

sqlcmd -S server -d database -U username -P password -o "somefile.csv" -h-1 
  -Q "exec myStoredProcedure 2011, 10" -W -w 2000 -s"," >> sometextfile.csv

注意第一个命令使用>,第二个命令使用>> ;。使用时-> “创建或覆盖”和两个-> “追加或创建”。

  • -h-1 删除 SQLCMD 生成的标题
  • -W 删除尾随空格
  • -w 设置最大行宽度
  • -s 定义列分隔符

To get rid of the hyphens, I add some code to my stored procedures that will output the column header only. Extracting data using SQLCMD is done in 2 parts.

First I call my stored procedure with a special set of parameters. In my case, when I call the SP with all NULLs, it mean I wish to have the column header.

Then I call SQLCMD a second time and append the output to the file that I just created before and voila!

Create a blank CSV file to hold the column header

sqlcmd -S server -d database -U username -P password -o "somefile.csv" -h-1 
  -Q "exec myStoredProcedure NULL, NULL" -W -w 2000 -s"," > sometextfile.csv

Now append the output result from the stored procedure

sqlcmd -S server -d database -U username -P password -o "somefile.csv" -h-1 
  -Q "exec myStoredProcedure 2011, 10" -W -w 2000 -s"," >> sometextfile.csv

Notice the first command uses > and the second one >>. When using one -> "Create or overwrite" and two -> "Append or create".

  • -h-1 removes the header generated by SQLCMD
  • -W removes the trailing spaces
  • -w set the max row width
  • -s defines columns separator
人事已非 2024-08-31 01:06:25

您可以执行以下操作:

exec 'sqlcmd -S YourServer -E -Q "set nocount on; select * from YourTable" -s "," -W | findstr /R /C:"^[^-]*$" > yourfile.csv'

这将一次性创建一个带有标题(不带破折号)并修剪了空格的 csv 文件。基于上面 MichaelM 的回答。

You can do the following:

exec 'sqlcmd -S YourServer -E -Q "set nocount on; select * from YourTable" -s "," -W | findstr /R /C:"^[^-]*$" > yourfile.csv'

This will create a csv file with the headers, without the dashes, and trimmed white space, in one fell swoop. Based on MichaelM's answer above.

烟织青萝梦 2024-08-31 01:06:25

我必须做大量的研究,因为这里没有一个答案完全符合我正在寻找的东西。所以我总结一下,希望对其他人有帮助。

对我来说,最简单的方法是使用 sed。虽然此处已建议这样做,但同时运行 sqlcmd 和 sed 的语法不正确。如果您使用的是 Windows,就像我一样,请前往 http://gnuwin32。 sourceforge.net/packages/sed.htm 下载 sed

我的最终命令如下所示:

SQLCMD -m 1 -S "userpc\SQLEXPRESS" -E -i "C:\someDirectory\sqlfile.sql" -W -s "," -o "C:\someDirectory\output.csv" && sed -i 2d "C:\someDirectory\output.csv"

其中

--m 1 消除了“将数据库上下文更改为...”行
-&& 如果第一个命令成功运行,则运行第二个命令
-sed -i 2d 删除包含连字符的第二行,并将 sed 的输出覆盖到原始输出

请注意 sed 输出文件名和 的输出>sqlcmd 必须匹配,否则 sqlcmd 的输出将不会被正确覆盖。正如上面回答的那样,在 sed 语句中的 2d 周围不应有引号,并且存在于其文档中,否则您将收到错误。

希望这有帮助!

I had to do a ton of research because none of the answers here exactly fit what I was looking for. So I am going to sum in hopes that it will help others.

For me, the easiest way was to use sed. While this was already suggested here, there was incorrect syntax to run sqlcmd and sed concurrently. If you're using Windows, as was the case for me, head to http://gnuwin32.sourceforge.net/packages/sed.htm to download sed

My final command looked something like:

SQLCMD -m 1 -S "userpc\SQLEXPRESS" -E -i "C:\someDirectory\sqlfile.sql" -W -s "," -o "C:\someDirectory\output.csv" && sed -i 2d "C:\someDirectory\output.csv"

Where

--m 1 eliminates the "Changed database context to..." line
-&& runs the second command if the first command runs successfully
-sed -i 2d deletes the second line containing the hyphens and overwrites the output of sed to the original output

Be aware that the sed output file name and the output from sqlcmd must match otherwise the output from sqlcmd will not be correctly overwritten. There should not be quotes around 2d in the sed statement as answered above and is present in their documentation or you will get an error.

Hope this helps!

揽月 2024-08-31 01:06:25

如果您可以使用 PowerShell 代替

工作示例:

Invoke-DbaQuery "SELECT * FROM [MyApp].[dbo].[ClientConfig] WHERE ClientID='Default'" -SqlInstance mysql.mydomain.com -ReadOnly `
  | Export-Csv -Path clientconfig-default.csv -Encoding utf8 -UseQuotes AsNeeded

注意 -ReadOnly 仅对集群有帮助,并且可能有噪音(早期优化)。但我是一名查询/比较生产数据库的开发人员,因此过于谨慎,因此尽量减少 DBA 可能注意到的负载。

我有时使用 https://docs.dbatools.io/#Copy-DbaDbTableData 复制整个表从 mssql 到 mssql。它很快,我认为使用 BCP.EXE 或 BulkInsert。

if you can use PowerShell instead

working example:

Invoke-DbaQuery "SELECT * FROM [MyApp].[dbo].[ClientConfig] WHERE ClientID='Default'" -SqlInstance mysql.mydomain.com -ReadOnly `
  | Export-Csv -Path clientconfig-default.csv -Encoding utf8 -UseQuotes AsNeeded

Note -ReadOnly is only helpful on clusters, and probably noise (early optimization). But I'm a developer querying/diffing production databases, so overly cautious so minimize load which might be noticed by DBAs.

I sometimes use https://docs.dbatools.io/#Copy-DbaDbTableData to copy whole tables mssql-to-mssql. It is fast, I think uses BCP.EXE or BulkInsert.

无远思近则忧 2024-08-31 01:06:25

如果您可以先输出到文件(使用 -o 选项),则使用 将通过读取文件内容(同时跳过第二行)并将其写回自身来工作。

(Get-Content "file.txt" | Where {$_.ReadCount -ne 2}) | Set-Content "file.txt"

If you could output to a file first (using the -o option), another post-process option using would work by reading the file's contents--while skipping the second line--and writing it back to itself.

(Get-Content "file.txt" | Where {$_.ReadCount -ne 2}) | Set-Content "file.txt"
眉目亦如画i 2024-08-31 01:06:25

MichaelM 有一个不错的解决方案,但正如 slingshot 指出的那样...... findstr 可能过于激进并删除包含连字符的数据行。另一种方法是调用 sqlcommand 来获取数据集,然后使用 set /p 从输出文件中获取第一行并将其分配给变量。然后删除原来的输出文件。接下来,将标头回显到新文件中。最后,将另一个无头 sqlcmd 通过管道传输到该文件。

sqlcmd -S server -d database -E -Q "exec myStoredProcedure" -W -o my_headers.csv -m-1
set /p headers=< my_headers.csv
del my_headers.csv
echo %headers% > my_data.csv
sqlcmd -S server -d database -E -Q "exec myStoredProcedure" -W -m-1 -h-1 >> my_data.csv

另外,Top 0 是创建“仅标头文件”的不错选择,但前提是您使用 select 语句。如果您正在调用存储过程,请考虑使用 FMTONLY ON 仅从 SP 获取标头。

sqlcmd -S server -d database -E -Q "Set NOCOUNT ON; Set FMTONLY ON; exec myStoredProcedure" -W -o my_headers.csv -m-1

需要注意的是 FMTONLY ON 可以'不能使用 #temp 表来对抗 SP。这是因为 FMTONLY ON 不执行 SP。它只获取元数据。但是,如果列名来自执行前不存在的表,那么您将无法获取这些列名。

  • 特洛伊

MichaelM has a decent solution, but as slingshot pointed out ... findstr could be over aggressive and remove data lines that contain hyphens. Another approach would be calling sqlcommand to get the data set and then using set /p to grab the first row from the output file and assign it to a variable. Then delete the orignal output file. Next, echo out the headers to a new file. Lastly, pipe another headerless sqlcmd to that file.

sqlcmd -S server -d database -E -Q "exec myStoredProcedure" -W -o my_headers.csv -m-1
set /p headers=< my_headers.csv
del my_headers.csv
echo %headers% > my_data.csv
sqlcmd -S server -d database -E -Q "exec myStoredProcedure" -W -m-1 -h-1 >> my_data.csv

Also Top 0 is nice choice to create a "headers only file" but only if you are using a select statement. If you're calling a stored procedure, look into using FMTONLY ON to grab the headers only from the SP.

sqlcmd -S server -d database -E -Q "Set NOCOUNT ON; Set FMTONLY ON; exec myStoredProcedure" -W -o my_headers.csv -m-1

A caveat being that the FMTONLY ON can't be used against SP's using #temp tables. This is because FMTONLY ON doesn't execute the SP. It only grabs metadata. But if the column names are coming from tables that don't exist pre-execution then you can't get those column names.

  • Troy
瑾兮 2024-08-31 01:06:25
Public Sub HyphenDelete(strFilename1 As String, Hyphens As Integer)


Const FOR_READING = 1
Const FOR_WRITING = 2

strFileName = strFilename1

strCheckForString = Left("-------", Hyphens)
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(strFileName, FOR_READING)
strContents = objTS.ReadAll
objTS.Close

arrLines = Split(strContents, vbNewLine)
Set objTS = objFS.OpenTextFile(strFileName, FOR_WRITING)

For Each strLine In arrLines
   If Not (Left(UCase(LTrim(strLine)), Len(strCheckForString)) = strCheckForString) Then
      objTS.WriteLine strLine
   End If
Next

End Sub
Public Sub HyphenDelete(strFilename1 As String, Hyphens As Integer)


Const FOR_READING = 1
Const FOR_WRITING = 2

strFileName = strFilename1

strCheckForString = Left("-------", Hyphens)
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(strFileName, FOR_READING)
strContents = objTS.ReadAll
objTS.Close

arrLines = Split(strContents, vbNewLine)
Set objTS = objFS.OpenTextFile(strFileName, FOR_WRITING)

For Each strLine In arrLines
   If Not (Left(UCase(LTrim(strLine)), Len(strCheckForString)) = strCheckForString) Then
      objTS.WriteLine strLine
   End If
Next

End Sub
甜嗑 2024-08-31 01:06:25

如果输出到文件,请在成功执行后尝试以下操作:

    findstr /v /c:"---" sqloutput.dat > finaloutput.dat

我使用“---”,因为我的所有列都超过 3 个字符,并且我的数据中从来没有该字符串,但您也可以使用“-;-”来降低风险进一步或基于您的数据的任何分隔符来代替“;”。

If outputting to a file try the following upon successful execution:

    findstr /v /c:"---" sqloutput.dat > finaloutput.dat

I use "---" as all my columns are over 3 characters and I never have that string in my data but you could also use "-;-" to reduce the risk further or any delimiter based on your data in place of the ";".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文