mardi 2 février 2016

SQL Server: stored procedure with several parameters

In the Stored procedure I would like change my code, for use it on other database. DATA: is name of a database I have other databases for example: DATA2 and DATA3. I need to replace DATA by parameter @LocalBase.

IF NOT EXISTS (SELECT * FROM ['' + @localBase + ''].SYS.SCHEMAS WHERE NAME = @DestinationSchema)        
    BEGIN
        SELECT @SQL = N'USE DATA; EXEC(''CREATE SCHEMA '' + @DestinationSchema + '')'
        EXEC sp_executesql @SQL
        INSERT INTO dbo.TableLog SELECT @id, @SourceServer, @SourceSchema, 'GetAllTables', @DestinationSchema, CURRENT_TIMESTAMP, 'Schema ' + @DestinationSchema + ' created', 2
    END

Is it possible (correct) to do this? `

@SQL=N'IF NOT EXISTS (SELECT * FROM ['' + @localBase + ''].SYS.SCHEMAS WHERE NAME = @DestinationSchema)'
EXEC sp_executesql @SQL

    BEGIN
        SELECT @SQL = N'USE ['' + @localBase + '']; EXEC(''CREATE SCHEMA '' + @DestinationSchema + '''')'
        EXEC sp_executesql @SQL
           INSERT INTO dbo.TableLog SELECT @id, @SourceServer, @SourceSchema, 'GetAllTables', @DestinationSchema, CURRENT_TIMESTAMP, 'Schema ' + @DestinationSchema + ' created', 2
    END

`

I would like to call the stored procedure like that:

DECLARE @RC int
DECLARE @SourceServer nvarchar(255)
DECLARE @localBase nvarchar(255)

SET @SourceServer = 'Serv1,10001'
SET @localBase = 'DATA1'

EXECUTE @RC = [dbo].[stor_proc_name] 
   @SourceServer,
   @localBase

Aucun commentaire:

Enregistrer un commentaire