-1

我尝试为 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 行

但实际情况是在物理表本身中看不到插入结果。我可以看到删除删除查询的结果。有谁知道为什么?

4

1 回答 1

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模式 - 这很容易在未来中断(有关更多详细信息,请参阅这篇文章)。另请参阅有关使用架构前缀的帖子和有关游标使用的这些帖子 - 它应该保留用于实际需要它的情况,并且当您确实需要它时,不要使用默认选项:

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 InstanceAttachDbFileName连接字符串中的选项)。

于 2013-10-05T15:34:53.533 回答