Management Studio T-SQL 쿼리에서 연결 지정


9

사용자를 DB 서버에 추가 할 때 GUI에서 "이 작업 스크립트"기능을 자주 사용합니다. 그런 다음 다른 서버에서 동일한 작업을 수행하기 위해 "연결 :: 연결 변경"으로 이동하십시오.

스크립트 작업에서 연결을 지정할 수있는 방법이 있습니까? 두 번째 연결 변경 단계를 수행 할 필요가 없습니까?

답변:


12

SSMS에서 스크립트의 일부로이 작업을 수행 할 수는 없지만 두 가지 옵션이 있습니다.

여러 서버에 연결하고 스크립트를 실행할 스크립트를 가지려면 SQLCMD 모드와 :: connect 명령을 사용하면됩니다. 이는 사용자의 스크립트를 저장하고 : r 명령을 사용하여 파일에서 스크립트를로드하는 경우에 효과적입니다.

수행 할 수있는 또 다른 작업은 중앙 관리 서버를 구성한 다음 한 번에 여러 서버에 대해 스크립트를 실행하는 것입니다.


1
"중앙 관리 서버". 아, 그건 내가 현재 사용하지 않는 것입니다 ...
— gbn

예, SQLCMD 스크립트보다 훨씬 나은 이런 것들에 대한 숨겨진 보석입니다.
— SQLRockstar

2

실제로 T-SQL 내에서 가능하지만 특정 조건 집합을 충족하고 몇 번의 후프를 뛰어 넘어야합니다.

  • 먼저 쿼리를 실행할 서버에서 원격 쿼리 (OPENDATASOURCE / OPENROWSET)를 활성화해야합니다.
  • 둘째, 대상 서버에 원격 액세스가 사용 가능한지 확인해야합니다.
  • 셋째, 실행할 대상 서버의 데이터베이스 엔진에 T-SQL 코드를 "주입"할 수 있도록 동적 SQL을 많이 사용해야합니다.

CMS를 활용하여 SQL 작업을 자동화 할 수있는 샘플 스크립트는 다음과 같습니다.

/**********************************************************************/

/* Global change password script                                      */

/*                                                                    */

/* This script changes the password for a SQL login on all servers    */

/* managed by a Central Management Server. It assumes that the login  */

/* exists on all servers, and that all servers are SQL 2005 or later. */

/**********************************************************************/

DECLARE @nServer NVARCHAR (128) -- Variable to hold the instance name retrieved from the CMS

DECLARE @nSQL NVARCHAR (4000)   -- Variable to hold dynamic SQL

DECLARE @ServerFetch INT        -- Variable to hold the fetch status. In SQL 2005, the @@FETCH_STATUS

                                -- variable is scoped at the system level, so if another process is also

                                -- using a cursor the @@FETCH_STATUS variable will be set according to

                                -- that operation. This allows us to store a persistent value.


DECLARE curServer CURSOR LOCAL STATIC FOR  -- Declare the cursor with the LOCAL and STATIC options, and

                                           -- retrieve the list of server names from the Central Management

                                           -- Server. The value in the [sysmanagement_shared_server_groups_internal]

                                           -- table is user-defined; for purposes of this example we have

                                           -- created a group named "SQL2008".

    SELECT DISTINCT

    s.server_name AS 'ServerName'

    FROM OPENDATASOURCE ('SQLOLEDB', 'Data Source = CMS1\Management; Integrated Security = SSPI').msdb.dbo.sysmanagement_shared_server_groups_internal g

    INNER JOIN OPENDATASOURCE ('SQLOLEDB', 'Data Source = CMS1\Management; Integrated Security = SSPI').msdb.dbo.sysmanagement_shared_registered_servers_internal s ON g.server_group_id = s.server_group_id

    WHERE g.name = 'SQL2008'

    ORDER BY s.server_name

OPEN curServer

FETCH FIRST FROM curServer INTO @nServer       -- Retrieve the first row

SET @ServerFetch = @@FETCH_STATUS              -- Store the status of the fetch operation

WHILE @ServerFetch = 0                         -- If the fetch was successful, we enter the loop. Otherwise

                                               -- execution passes to the statement following the END statement.

    BEGIN

    -- Build the dynamic SQL to alter the password for the SQL login.

    SET @nSQL = 'EXEC OPENDATASOURCE (''SQLOLEDB'', ''Data Source = ' + @nServer

        + '; Integrated Security = SSPI'').master.dbo.sp_executesql N''ALTER LOGIN SQLLogin WITH PASSWORD = ''''<enterStrongPasswordHere>'''''

    -- Execute the dynamic SQL.

    EXEC sp_executesql @nSQL

    FETCH NEXT FROM curServer INTO @nServer    -- Retrieve the next row.

    SET @ServerFetch = @@FETCH_STATUS          -- Store the status of the fetch operation.

    END

CLOSE curServer        -- Close the cursor.

DEALLOCATE curServer   -- Remove the cursor from memory.

1

아니요.로만 데이터베이스 USE Database. 연결은 스크립트 가능하지 않습니다.

SSMS 2008 (?) 및 기타 도구는 "여러 서버에서 실행"기능을 제공합니다. 죄송합니다. 현재 역할에서이 기능을 사용하지 않으므로이 문제가 없습니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.