我需要一些关于这个查询的帮助,我正在尝试运行它,但我一直在得到的是
"There is already an object named '#PreFixedData1' in the database."
您能否告知解决方法,以便使用嵌套的IF Exists语句将数据输入?我也尝试在第一个ELSE IF EXISTS
之后使用IF EXISTS
,但我收到同样的错误。
CREATE TABLE dbo.PostPivotTbl (
TestDate VARCHAR(100)
);
GO
INSERT INTO dbo.PostPivotTbl
VALUES ('17/Jul/2014'),
'10/May/2014' )
IF EXISTS (
SELECT TestDate
FROM dbo.PostPivotTbl
WHERE TestDate LIKE '[1-9]%' AND TestDate NOT LIKE '0%' AND TestDate NOT LIKE '%/%'
)
BEGIN
IF OBJECT_ID('tempdb..#PreFixedData1', 'u') IS NOT NULL DROP TABLE #PreFixedData1
SELECT
CAST(TestDate AS INT) AS 'TestDate'
INTO #PreFixedData1
FROM dbo.PostPivotTbl
END
ELSE
BEGIN
IF EXISTS(
SELECT TestDate
FROM dbo.PostPivotTbl
WHERE TestDate
LIKE '%2013%' AND TestDate LIKE '%-%' OR TestDate LIKE '%2014%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%2013%' AND TestDate LIKE '%/%' OR TestDate LIKE '%2014%' AND
TestDateLIKE '%/%'
OR TestDate LIKE '%2012%' AND TestDate LIKE '%/%'
OR
TestDate LIKE '%Jan%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Feb%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Mar%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Apr%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%May%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Jun%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Jul%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Aug%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Sep%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Oct%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Nov%' AND TestDate LIKE '%-%'
OR
TestDate LIKE '%Dec%' AND TestDate LIKE '%-%'
)
BEGIN
IF OBJECT_ID('tempdb..#PreFixedData1', 'u') IS NOT NULL DROP TABLE #PreFixedData1
SELECT
CAST(TestDate AS DATETIME) AS 'TestDate'
INTO #PreFixedData1
FROM dbo.PostPivotTbl
END
END
答案 0 :(得分:3)
这与EXISTS
子句(顺便说一下看起来非常混乱)无关,它与SQL Server编译语句的方式有关。您只需使用以下命令重新创建:
IF 1 = 0
BEGIN
SELECT Col = 1
INTO #T;
END
ELSE
BEGIN
SELECT Col = 2
INTO #T;
END
出现错误:
数据库中已有一个名为“#T”的对象。
即使只能跟踪IF语句的一个分支,SQL Server也会对它们进行编译,因此当它编译第二个分支时,它会建立#T
将存在,因此抛出编译错误。
工作周围是创建一次表,并使用INSERT [Table] SELECT..
:
CREATE TABLE #PreFixedData1 (TestDateInt INT, TestDate DATETIME);
IF ...
INSERT #PreFixedData1 (TestDateInt)
SELECT ....
ELSE
INSERT #PreFixedData1 (TestDate)
SELECT ...
这超出了问题的范围,但我不知道为什么要创建一个VARCHAR(100)
的列然后向其插入日期。保留日期和日期,如果它是有效日期,您不需要进行各种奇怪的比较。我也不确定为什么要有条件地创建相同的表但是根据表中的数据使用不同的数据类型。
另外,使用string literals as column aliases is on the deprecation list(SELECT Column AS 'Alias'
)