データ型の指定
日付型(date)の指定: 'yyyy-mm-dd'
日時型(datetime)の指定: 'yyyy-mm-dd hhss.nnn'
LIKE述語
%: 任意の文字(0文字含む)
-: 任意の一文字
[例]
- 「高」を含む: WHERE 列名 LIKE '%高%'
- 「高」で始まる: WHERE 列名 LIKE '高%'
- 「高」で始まる3文字: WHERE 列名 LIKE '高__'
バッチファイルからSQLを実行
SQLServerをインストールしている環境では、sqlcmdを使うことができる。
Windows認証でServer接続
set Server=%COMPUTERNAME%\SQLEXPRESS
echo %Server%
CD %~dp0
SQLCMD -S %Server% -i input.txt -s, -W -o output.txt
pause
USE [testDB]
GO
SELECT * FROM [dbo].[DATATABLE];
GO
sqlファイルに引数を渡す
バッチファイルからSQLが書かれたファイル(sqlファイル)に引数を渡す。
set Server=%COMPUTERNAME%\SQLEXPRESS
echo %Server%
CD %~dp0
SQLCMD -S %Server% -i input.txt -v start_date="2017-07-01 00:00:00" -s, -W -o output.txt
pause
USE [testDB]
GO
SELECT * FROM [dbo].[DATATABLE] WHERE [file_start_date] > '$(start_date)';
GO
sqlcmd オプション
sqlcmd
-a packet_size
-A (dedicated administrator connection)
-b (terminate batch job if there is an error)
-c batch_terminator
-C (trust the server certificate)
-d db_name
-e (echo input)
-E (use trusted connection)
-f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
-g (enable column encryption)
-G (use Azure Active Directory for authentication)
-h rows_per_header
-H workstation_name
** -i input_file **
-I (enable quoted identifiers)
-j (Print raw error messages)
-k[1 | 2] (remove or replace control characters)
-K application_intent
-l login_timeout
-L[c] (list servers, optional clean output)
-m error_level
-M multisubnet_failover
-N (encrypt connection)
** -o output_file **
-p[1] (print statistics, optional colon format)
-P password
-q "cmdline query"
-Q "cmdline query" (and exit)
-r[0 | 1] (msgs to stderr)
-R (use client regional settings)
-s col_separator
** -S [protocol:]server[instance_name][,port] **
-t query_timeout
-u (unicode output file)
-U login_id
** -v var = "value" **
-V error_severity_level
-w column_width
** -W (remove trailing spaces) **
-x (disable variable substitution)
-X[1] (disable commands, startup script, environment variables, optional exit)
-y variable_length_type_display_width
-Y fixed_length_type_display_width
-z new_password
-Z new_password (and exit)
-? (usage)