我希望每天执行一次存储过程,该过程将首先删除指定表中的数据,然后将新数据插入其中。
我的存储过程大致如下
ALTER PROCEDURE [dbo].[SP_Name]
AS BEGIN
WITH CTE_Name as
( select
Title,
First_Name,
Surname
From table
)
DELETE [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
Select * from CTE_NAME
END
执行查询时,我得到错误的无效对象名称'CTE_NAME'
我尝试删除'DELETE [dbo]。[NEW_TABLE]'行,执行此操作后,存储过程便会运行并将数据插入表中。
我正在使用SQl Management Studio 2012
答案 0 :(得分:0)
您可以尝试以下代码:
ALTER PROCEDURE [dbo].[SP_Name] AS
BEGIN
DECLARE @helperTbl TABLE (Title varchar(100), First_Name varchar(100), Surname varchar(100))
INSERT INTO @helperTbl
SELECT Title,
First_Name,
Surname
FROM [table]
DELETE FROM [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
SELECT * FROM @helperTbl
END
答案 1 :(得分:0)
我认为您需要通过在其前面添加分号来分隔您的With
下面的代码应该可以工作
DECLARE @TABLE TABLE (
id VARCHAR(100)
)
DELETE FROM @TABLE
;WITH CTE_Name AS
(
SELECT id FROM OtherTable
)
INSERT INTO @TABLE
SELECT id FROM CTE_Name