views:

50

answers:

3

I have this simple little batch file program that I wrote but it fails if I enter a database name that contains a "-" character. Im not exactly sure why but I wish I could figure out a way around this?

:: open DB batch file
@echo off
:: starts Sql Server Management Studio Express 2005
:: and opens it to a specific database with query
:: window already open

cls

:SHOWDBNAMES
echo Database names detected on this system:
echo.
"%PROGRAMFILES%\Microsoft SQL Server\90\Tools\Binn\OSQL.EXE" -h-1 -S . -E -Q "SELECT CAST(name AS VARCHAR(30)) FROM sysdatabases"

@echo.
set DBNAME=
set /P DBNAME=What database name would you like to open (choose from list)? 

if "%DBNAME%" == "" (
  echo.
  echo I don't recognize your selection. Try again.
  goto SELECTDB
)

:SHOWTABLES
cls
echo.
echo Tables that you can query from %DBNAME% are:
echo.
"%PROGRAMFILES%\Microsoft SQL Server\90\Tools\Binn\OSQL.EXE" -h-1 -S . -E -Q "use [%DBNAME%];SELECT CAST(name AS VARCHAR(30)) FROM sys.Tables ORDER BY name"
echo.

:RUNIT
sqlwb.exe -nosplash -S . -E -d %DBNAME%

pause
:EOF
A: 

Why don't you just try an underscore (_)?

dewalla
I want my script to support all conditions including a '-' character.
djangofan
A: 

Is it failing on the sqlwb.exe line when the dash is the first letter in the database name? If so, your problem is that sqlwb is misinterpreting the database name as a command line option. There should be some way to make it not do that; check the manual.

Zack
no, it fails on the sys.Tables query only. everywhere else it works.
djangofan
+2  A: 

Try enclosing the database name in square brackets:

[database-name]

EDIT

The following should work - you need to quote the database name in the call to sqlwb.exe:

:SHOWTABLES
cls
echo.
echo Tables that you can query from %DBNAME% are:
echo.
"%PROGRAMFILES%\Microsoft SQL Server\90\Tools\Binn\OSQL.EXE" -h-1 -S . -E -Q "SELECT CAST(name AS VARCHAR(30)) FROM [%DBNAME%].sys.Tables ORDER BY name"
echo.

:RUNIT
sqlwb.exe -nosplash -S . -E -d "%DBNAME%"

I've got to ask though - what's the point of this script? The built-in SSMS object explorer gives you all this information for free.

Also, your script doesn't take account of SQL server instances other than the default - SQL Server Express is installed as <machine_name>\SQLEXPRESS by default.

Ed Harper
tried it. doesn't solve the problem with the sys.Tables query. I tried "use [database-name]; select ....."
djangofan
i think OSQL.exe , being a .exe program, thinks that all "-" chars means a new argument to the executable. thats my best guess.
djangofan
@djangofan - I've updated my answer with an edit which should work.
Ed Harper
thanks. that worked. the reason for the script is that is a few seconds faster than opening SSSME and then clicking through the "Connect Object Explorer". This script will save me 5+ seconds for each time I want to open SSSME.
djangofan