我有一个使用临时表的存储过程。问题是我尝试在不同的SELECT INTO
语句中多次使用临时表。当然,在发布下一个声明之前我已经发布了一个DROP #TempTableName
然后发布SELECT INTO
声明。显然这个DROP
语句是不够的,因为下一个SELECT INTO
语句抱怨对象#TempTableName
已经存在 - SSMS 输出是:
消息 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