我尝试为MS SQL创建存储过程
CREATE PROCEDURE YEARENDPROCESSING
AS
DECLARE @VAR AS VARCHAR(9)
DECLARE ACURSOR CURSOR FOR
SELECT COLUMN FROM TABLEA
OPEN ACURSOR
FETCH NEXT FROM ACURSOR INTO @VAR
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TABLEB SELECT * FROM TABLEC WHERE TABLEC.COLUMNC = @VAR
FETCH NEXT FROM ACURSOR INTO @VAR
END
CLOSE ACURSOR
DEALLOCATE ACURSOR
假设TableC列和TableB具有相同的列 我得到结果说X行受到影响 但在实际的表格中,我什么也看不见。
我有一个新的发现
CREATE PROCEDURE YEARENDPROCESSING
AS
DECLARE @VAR AS VARCHAR(9)
DECLARE ACURSOR CURSOR FOR
SELECT COLUMN FROM TABLEA
OPEN ACURSOR
FETCH NEXT FROM ACURSOR INTO @VAR
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TABLEB SELECT * FROM TABLEC WHERE TABLEC.COLUMNC = @VAR
DELETE TABLEF where columnf = @VAR
FETCH NEXT FROM ACURSOR INTO @VAR
END
CLOSE ACURSOR
DEALLOCATE ACURSOR
对于插入而言,x行会受到影响,而对于删除
,x行会受到影响但实际的事实是在物理表本身中无法看到插入结果。我可以看到删除删除查询的结果。谁知道为什么?
答案 0 :(得分:3)
您的代码不应该有光标。你可以这样做:
CREATE PROCEDURE dbo.YearEndProcessing
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.TableB(column1, column2, ...)
SELECT column1, column2, ...
FROM dbo.TableA;
END
GO
嗯,你改变了代码,现在有第三个表,所以让我在没有光标的情况下再试一次:
CREATE PROCEDURE dbo.YearEndProcessing
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.TableB(column1, column2, ...)
SELECT c.column1, c.column2, ...
FROM dbo.TableA AS a
INNER JOIN dbo.TableC AS c
ON a.[Column] = c.[ColumnC];
END
GO
或者:
CREATE PROCEDURE dbo.YearEndProcessing
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.TableB(column1, column2, ...)
SELECT c.column1, c.column2, ...
FROM dbo.TableC AS c
WHERE EXISTS
(
SELECT 1 FROM dbo.TableA AS a
WHERE a.[Column] = c.[ColumnC]
);
END
GO
你不应该使用INSERT TABLE SELECT * FROM TABLE
模式 - 将来很容易破坏(see this post for more details)。另请参阅this post about using a schema prefix以及有关游标用法的这些帖子 - 它应该保留用于实际需要它的情况,当您确实需要它时,请不要使用默认选项:
https://sqlblog.org/2012/01/26/bad-habits-to-kick-thinking-a-while-loop-isnt-a-cursor
http://www.sqlperformance.com/2012/07/t-sql-queries/running-totals
http://www.sqlperformance.com/2012/09/t-sql-queries/cursor-options
至于为什么你看到插入行但后来看不到数据,我怀疑你正在查看错误数据库中的表,错误的模式,或者你有多个数据库副本(发生了这种情况)在连接字符串中使用User Instance
和AttachDbFileName
选项时。)