sql - 将标量查询结果返回到批处理文件变量中

标签 sql sql-server batch-file

我想执行标量数据库查询并将结果返回到批处理文件中的变量中。

如何做到这一点?我在我们的系统中看到的最接近的示例是,如果我根据标量查询结果返回退出代码。

    Z:\SQL2005\90\Tools\Binn\sqlcmd -S servername -dCLASS -E -Q "EXIT(select case run_type when 'Q' then 200 else 100 end from cycle_date where cycle = '1')">NUL
    if %errorlevel% == 200 call %SQLSERVER%
QRTLY.BAT               
    if %errorlevel% == 100 call %SQLSERVER%
MTHLY.BAT

有人可以帮我解决语法问题吗?

这是一些 sqlcmd 帮助信息:

-v var = value[ var=value...] 
Creates a sqlcmdscripting variable that can be used in a sqlcmd script. Enclose the value in quotation marks if the value contains spaces. You can specify multiple var="values" values. If there are errors in any of the values specified, sqlcmd generates an error message and then exits.

sqlcmd -v MyVar1=something MyVar2="some thing" 

sqlcmd -v MyVar1=something -v MyVar2="some thing" 

-x disable variable substitution 
Causes sqlcmd to ignore scripting variables. This is useful when a script contains many INSERT statements that may contain strings that have the same format as regular variables, such as $(variable_name).

最佳答案

如何将其保存到没有标题的文件中,然后读回内容?

sqlcmd -S(local)\SQLExpress -dMyDatabase -Umyuser -Pmypassword -W -h -1 -Q  "SELECT Top 1 MyValue FROM MyTable" -o sqlcmdoutput.txt 
set /p x= <sqlcmdoutput.txt
del sqlcmdoutput.txt
echo My scalar value is %x%

关于sql - 将标量查询结果返回到批处理文件变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6793382/

相关文章:

MySQL SELECT 查询字符串分割搜索值

mysql - 在 mysql 中尝试跨数据库更新时找不到列

php - 在函数中使用 "return"后是否执行了任何操作

php - 在 PHP、MySQL 中,如何使用 HTML 表单更新表格中的一行

php - 选择多个条件

c# - 如何使用 C# 将数组的元素插入到 SQL Server 数据库中?

sql - where 子句中的函数调用

command-line - 如何在批处理文件中循环匹配通配符的文件

c++ - 如何创建生成 XML 并随后运行 DOS 命令的 C/C++ 程序?

windows - 批量 - 解析相对路径