我正在使用if else语句,我想删除在内部if语句旁边创建的临时表,但是当我执行语句时,我得到答案为,已经有一个名为&#39的对象;#表'在数据库中。 ---------------------我的代码就像在这里输入代码一样
DECLARE @RowCount INT;
SET @RowCount = 1;
IF @RowCount = 1
BEGIN
IF OBJECT_ID('tempdb..#Guarantor_Details') IS NOT NULL
DROP TABLE #Guarantor_Details
SELECT DISTINCT TOP 1 GUARANTORS.GUARANTOR_CODE
INTO #Guarantor_Details
FROM GUARANTORS
WHERE ISNULL(GUARANTORS.deleted, 0) <> 1;
DECLARE @GuarantorCount INT;
SELECT @GuarantorCount = count(*)
FROM #Guarantor_Details;
IF (@GuarantorCount = 0)
DROP TABLE #Guarantor_Details
BEGIN
IF OBJECT_ID('tempdb..#Guarantor_Details') IS NOT NULL
SELECT TOP 1 CLIENT.Last_Name
INTO #Guarantor_Details
FROM CLIENT
LEFT JOIN GUARANTORS ON GUARANTORS.GUARANTOR_CODE = CLIENT.Financial_Guarantor
END
END
------------------------------------------------------------------------
答案 0 :(得分:0)
您不需要执行此类型的CREATE / DROP。您可以(也可能应该)在循环之前创建表,并在需要“重置”它时简单地TRUNCATE TABLE
或DELETE FROM
临时表。只需选择适合GUARANTOR_CODE
和Last_Name
的数据类型。
当您拥有SELECT COUNT(*)
操作中已有该值的@@ROWCOUNT
时,您也无需在桌面上执行INSERT
。
本质:
CREATE TABLE #Guarantor_Details (Value NVARCHAR(50));
WHILE (something)
BEGIN
IF (@RowCount = 1)
BEGIN
TRUNCATE TABLE #Guarantor_Details;
INSERT INTO #Guarantor_Details (Value)
SELECT DISTINCT TOP 1 GUARANTORS.GUARANTOR_CODE
FROM GUARANTORS
WHERE ISNULL(GUARANTORS.deleted, 0) <> 1;
IF (@@ROWCOUNT = 0)
BEGIN
INSERT INTO #Guarantor_Details (Value)
SELECT TOP 1 CLIENT.Last_Name
FROM CLIENT
LEFT JOIN GUARANTORS
ON GUARANTORS.GUARANTOR_CODE = CLIENT.Financial_Guarantor;
END;
END;
仅供参考,出现是原始代码中的一些逻辑问题:
IF @RowCount = 1
块底部有BEGIN / END标记,与任何IF或WHILE无关。这在技术上是可以的,但通常意味着缺少某些东西。
如果此代码是所有代码,则IF @RowCount = 1
在循环中不起作用,除非将@RowCount
设置为超出此外部IF块的末尾(此处未显示)在问题中。