Stored procedure to create a database which table definitions are on a T-SQL file

  • So... whats the problem?

    [font="Times New Roman"]-- RBarryYoung[/font], [font="Times New Roman"] (302)375-0451[/font] blog: MovingSQL.com, Twitter: @RBarryYoung[font="Arial Black"]
    Proactive Performance Solutions, Inc.
    [/font]
    [font="Verdana"] "Performance is our middle name."[/font]

  • Opps I forgot to state the issue, the problem is that all the T-SQL code inside the file doesn't get executed properly on the new scope (USE @DBName)

    I'd like to run all the code from the file against the newly created database.

    I hope it's clear now 😀

    ...Alex

  • The use statement that you specified is not going to ever help. The OSQL command executes in its own context, and will go to the default database for whatever user SQL is running under.

    DECLARE @DBName varchar(128)

    SET @DBName = 'DEMO'

    DECLARE @cmd varchar(300)

    IF DB_ID(@DBName) IS NULL

    BEGIN

    SELECT @cmd = 'CREATE DATABASE ' + @DBName

    EXEC ( @cmd )

    SELECT @cmd = 'osql -E -n -S' + @@SERVERNAME + ' -d' + @DBName + ' -i"C:\Temp\MySQLFile.sql" '

    EXEC master..xp_cmdshell @cmd

    END

    This should be real close and somewhat more resilient that the original.

    CEWII

  • Works great! Thanks a bunch! 😀

    ...Alex

  • You are welcome.

    CEWII

Viewing 5 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply