Is it possible to execute a text file from SQL query?

后端 未结 9 917
星月不相逢
星月不相逢 2020-12-04 21:35

I have a number of generated .sql files that I want to run in succession. I\'d like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studi

相关标签:
9条回答
  • 2020-12-04 22:20

    Or just use openrowset to read your script into a variable and execute it (sorry for reviving an 8 years old topic):

    DECLARE @SQL varchar(MAX)
    SELECT @SQL = BulkColumn
    FROM OPENROWSET
        (   BULK 'MeinPfad\MeinSkript.sql'
        ,   SINGLE_BLOB ) AS MYTABLE
    
    --PRINT @sql
    EXEC (@sql)
    
    0 讨论(0)
  • 2020-12-04 22:24

    This is what I use. Works well and is simple to reuse. It can be changed to read all files in the directory, but this way I get to control which ones to execute.

    /*  
    execute a list of .sql files against the server and DB specified  
    */  
    SET NOCOUNT ON  
    
    SET XACT_ABORT ON  
    BEGIN TRAN  
    
    DECLARE @DBServerName   VARCHAR(100) = 'servername'  
    DECLARE @DBName VARCHAR(100) = 'db name'  
    DECLARE @FilePath   VARCHAR(200) = 'path to scrips\'  
    /*
    
    create a holder for all filenames to be executed  
    
    */  
    DECLARE @FileList TABLE (Files NVARCHAR(MAX))  
    
    INSERT INTO @FileList VALUES ('script 1.sql')  
    INSERT INTO @FileList VALUES ('script 2.sql')  
    INSERT INTO @FileList VALUES ('script X.sql')  
    
    WHILE (SELECT COUNT(Files) FROM @FileList) > 0  
    BEGIN  
       /*  
       execute each file one at a time  
       */  
       DECLARE @FileName NVARCHAR(MAX) = (SELECT TOP(1) Files FROM @FileList)  
       DECLARE @command  VARCHAR(500)  = 'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i "' + @FilePath + @Filename +'"'  
       EXEC xp_cmdshell  @command   
    
       PRINT 'EXECUTED: ' + @FileName     
       DELETE FROM @FileList WHERE Files = @FileName  
    END  
    COMMIT TRAN  
    
    0 讨论(0)
  • 2020-12-04 22:26

    use xp_cmdshell and sqlcmd

    EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName
    
    0 讨论(0)
提交回复
热议问题