一時テーブルを使用するストアド プロシージャがあります。SELECT INTO
問題は、一時テーブルを異なるステートメントで複数回使用しようとしたことです。もちろん、次のステートメントを発行する前に、ステートメントを発行してから発行しましDROP #TempTableName
たSELECT INTO
。次のステートメントはオブジェクトが既に存在することを訴えているため、明らかにこのDROP
ステートメントでは不十分です。SSMS の出力は次のとおりです。SELECT INTO
#TempTableName
メッセージ 2714、レベル 16、状態 1、手順 SYNC_SpreadMembers、行 23
データベースには、'#MM_SYNC_MEMBERS' という名前のオブジェクトが既に存在します。
そして、ここに私のT-SQLコードがあります:
CREATE PROCEDURE SYNC_SpreadMembers
AS
BEGIN
BEGIN
-- Member
IF (OBJECT_ID('tempdb..#MM_SYNC_MEMBERS') IS NOT NULL)
DROP TABLE #MM_SYNC_MEMBERS;
-- Imported members
SELECT DISTINCT MemberInr INTO #MM_SYNC_MEMBERS FROM
(
SELECT DISTINCT DmInr AS MemberInr FROM MM_SYNC_EBOLIGWS WHERE NOT DmInr IS NULL
UNION
SELECT DISTINCT AmInr AS MemberInr FROM MM_SYNC_EBOLIGWS WHERE NOT AmInr IS NULL
) MemberHeap
;
DELETE #MM_SYNC_MEMBERS FROM #MM_SYNC_MEMBERS Sync INNER JOIN MM_Member Member ON Sync.MemberInr = Member.InteressentNr;
INSERT INTO MM_Member(InteressentNr) SELECT MemberInr FROM #MM_SYNC_MEMBERS;
END
-- Hardcoded members
DROP TABLE #MM_SYNC_MEMBERS;
SELECT DISTINCT InteressentNr AS MemberInr INTO #MM_SYNC_MEMBERS FROM MM_SYNC_HardcodedMemberRoles;
DELETE #MM_SYNC_MEMBERS FROM #MM_SYNC_MEMBERS Sync INNER JOIN MM_Member Member ON Sync.MemberInr = Member.InteressentNr;
INSERT INTO MM_Member(InteressentNr) SELECT MemberInr FROM #MM_SYNC_MEMBERS;
-- MemberRole
-- Area Managers
DELETE MM_MemberRole;
INSERT INTO MM_MemberRole(MemberSid, RoleSid)
SELECT DISTINCT Member.[Sid], (SELECT [Sid] FROM MM_Role WHERE Cipher LIKE 'AMA')
FROM MM_SYNC_EBOLIGWS Sync
INNER JOIN MM_Member Member ON Sync.AmInr = Member.InteressentNr
WHERE Sync.AmInr IS NOT NULL
;
-- Department Managers
INSERT INTO MM_MemberRole(MemberSid, RoleSid)
SELECT DISTINCT Member.[Sid], (SELECT Sid FROM MM_Role WHERE Cipher LIKE 'DM')
FROM MM_SYNC_EBOLIGWS Sync
INNER JOIN MM_Member Member ON Sync.DmInr = Member.InteressentNr
WHERE Sync.DmInr IS NOT NULL
;
-- Hardcoded Roles
INSERT INTO MM_MemberRole(MemberSid, RoleSid)
SELECT Member.Sid, Roles.Sid
FROM MM_SYNC_HardcodedMemberRoles HCR
INNER JOIN MM_Member Member ON HCR.InteressentNr = Member.InteressentNr
INNER JOIN MM_Role Roles ON HCR.RoleCipher = Roles.Cipher
;
END
GO