Read 1st line of a file in t-sql

  • I'm writing a script-running routine in t-sql. Long story. Yes, it has to be t-sql.

    So I have the full script path at this particular point in my script, which is cursoring through a list of scripts. I also have the execution step down. What I need to do is ensure that the 1st line of the file is a USE statement.

    I've been looking around all morning and have found repeated scripts that load all of the scripts from a directory into values in a temp table and then reading the contents. I don't want to do anything directory-wide. These directories hold 100s of scripts, some of which contain 10's of 1000's of lines of code. It has to be targeted to just look at the exact file for the path I can provide.

    Can someone help me out? I can put functions and/or stored procs to use.

    an example value in my path variable:

    \\DEVDBREGQA01\SQL_SCRIPTS\DB_NAME\TABLES\someScript.sql

    Thanks in advance

  • I suggest trying the BULK INSERT command, since you can stop it after only one row. Specify a never-found field terminator to make sure you read the entire first line.

    CREATE TABLE #text_row (

    text_row varchar(8000)

    )

    BULK INSERT #text_row

    FROM '\\DEVDBREGQA01\SQL_SCRIPTS\DB_NAME\TABLES\someScript.sql'

    WITH

    (

    FIELDTERMINATOR = '~~~~~~',

    LASTROW = 1, --or = 2 to be sure

    ROWTERMINATOR ='bn' --EDIT: where b = backslash, but backslash_n that doesn't show up on the screen

    )

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Have you seen this solution[/url] at Simple Talk?

    I haven't used it myself, but it looks interesting.

    Brandie Tarvin, MCITP Database AdministratorLiveJournal Blog: http://brandietarvin.livejournal.com/[/url]On LinkedIn!, Google+, and Twitter.Freelance Writer: ShadowrunLatchkeys: Nevermore, Latchkeys: The Bootleg War, and Latchkeys: Roscoes in the Night are now available on Nook and Kindle.

Viewing 3 posts - 1 through 2 (of 2 total)

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