我必须有一个临时表来存储一些memberIds。我需要每次都删除该表,因为我希望它的数据始终是新鲜的和更新的。但是我需要在每次重新创建它之前都将其删除。但是似乎SQL Server无法以某种方式执行我的整个脚本。
IF OBJECT_ID('tempdb.dbo.#available_memberIds', 'U') IS NOT NULL
BEGIN
DROP TABLE #available_memberIds;
CREATE TABLE #available_memberIds (
memberId Int,);
Insert into #available_memberIds SELECT memberId
FROM tbl_attendancemembers
WHERE memberId NOT IN
(SELECT memberId
FROM tbl_attendanceSheet)
UNION
SELECT memberId
FROM tbl_attendancemembers
WHERE memberId IN
( SELECT memberId
FROM tbl_attendanceSheet
GROUP BY memberId, date
HAVING COUNT(*) <= 1)
END
当我突出显示整个代码并执行它时,它表示执行成功。但是当我select * from #available_memberIds
时,它没有显示任何memberId,这意味着它没有在表中插入任何内容。尽管当我仅分别突出显示Insert Into
部分和select * from #available_memberIds
时,它显示的是memberId。
我是否还需要为IF条件写一些东西?我复制了除drop部分以外的所有内容,其余部分都复制了,但是当我执行整个代码(包含else部分)时,它总是说
在该目录中已经有一个名为“ #available_memberIds”的对象 数据库。
这很奇怪,因为当我仅突出显示放置部分并执行它时,它说>无法放置表格
'#available_memberIds',因为它不存在或您没有 许可。
当我select * from #available_memberIds
时说:
无效的对象名称'#available_memberIds'。
IF OBJECT_ID('tempdb.dbo.#available_memberIds', 'U') IS NOT NULL
BEGIN
DROP TABLE #available_memberIds;
CREATE TABLE #available_memberIds (
memberId Int,);
BEGIN
Insert into #available_memberIds SELECT memberId
FROM tbl_attendancemembers
WHERE memberId NOT IN
(SELECT memberId
FROM tbl_attendanceSheet)
UNION
SELECT memberId
FROM tbl_attendancemembers
WHERE memberId IN
( SELECT memberId
FROM tbl_attendanceSheet
GROUP BY memberId, date
HAVING COUNT(*) <= 1)-- and date=@inputdate)
END
END
ELSE
BEGIN
CREATE TABLE #available_memberIds (
memberId Int,);
BEGIN
Insert into #available_memberIds SELECT memberId
FROM tbl_attendancemembers
WHERE memberId NOT IN
(SELECT memberId
FROM tbl_attendanceSheet)
UNION
SELECT memberId
FROM tbl_attendancemembers
WHERE memberId IN
( SELECT memberId
FROM tbl_attendanceSheet
GROUP BY memberId, date
HAVING COUNT(*) <= 1)-- and date=@inputdate)
END
END
我正在Visual Studio数据库管理器中编写SQL代码
答案 0 :(得分:0)
您可以使用类似这样的东西。然后将您的代码放在后面。确保在tempdb和您的临时表之间有两个点。然后,您不需要多个语句,它只会删除它,然后每次都重新创建它。
IF OBJECT_ID('tempdb..#available_memberIds') IS NOT NULL
DROP TABLE #available_memberIds;
...
SELECT memberId
INTO #available_memberIds
FROM tbl_attendancemembers
WHERE memberId NOT IN
(SELECT memberId
FROM tbl_attendanceSheet)
UNION
SELECT memberId
FROM tbl_attendancemembers
WHERE memberId IN
( SELECT memberId
FROM tbl_attendanceSheet
GROUP BY memberId, date
HAVING COUNT(*) <= 1)-- and date=@inputdate)
END