2

I have created a sqlcmd startup script that i have stored in c:\myscript.sql, and I want it to run every time i start sqlcmd. how do I configure sqlcmd to automatically run your script every time it starts?

1

It is documented in BOL

E. Using a startup script

A sqlcmd startup script is executed when sqlcmd is started. The following example sets the environment variable SQLCMDINI. This is the contents of init.sql.

SET NOCOUNT ON
GO
DECLARE @nt_username nvarchar(128)
SET @nt_username = (SELECT rtrim(convert(nvarchar(128), nt_username))
FROM sys.dm_exec_sessions WHERE spid = @@SPID)
SELECT @nt_username + ' is connected to ' +
rtrim(CONVERT(nvarchar(20), SERVERPROPERTY('servername'))) +
' (' +
rtrim(CONVERT(nvarchar(20), SERVERPROPERTY('productversion'))) +
')'
:setvar SQLCMDMAXFIXEDTYPEWIDTH 100
SET NOCOUNT OFF
GO
:setvar SQLCMDMAXFIXEDTYPEWIDTH

This calls the init.sql file when sqlcmd is started.

C:\> SET sqlcmdini=c:\init.sql
>1 Sqlcmd

This is the output.

>1 < user > is connected to < server > (9.00.2047.00)
1

You will need to set the SQLCMDINI variable in Windows. For example:

C:\SET SQLCMDINI=c:\sqlscripts\init.sql

The init.sql (or whatever you name it) would contain the initial script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.