执行两次执行相同语句的过程

时间:2014-02-27 05:34:13

标签: sql-server sql-server-2008-r2

我写过这个程序,

DECLARE CURS_TABLE CURSOR FOR 
SELECT NAME FROM SYS.TABLES WHERE NAME LIKE 'AK_LIB_ADDRESS'
DECLARE @TABLE_NAME VARCHAR(100);
DECLARE @SQL VARCHAR(300);
OPEN CURS_TABLE
FETCH NEXT FROM CURS_TABLE INTO @TABLE_NAME;

WHILE @@FETCH_STATUS = 0
BEGIN
  SET @SQL = 'ALTER TABLE '+@TABLE_NAME+' ADD PRIMARY KEY(ID);';
  EXEC (@SQL)
  FETCH NEXT FROM CURS_TABLE INTO @TABLE_NAME
END

CLOSE CURS_TABLE;
DEALLOCATE CURS_TABLE;

问题是exec(@sql)执行相同的语句两次,我通过放置print语句检查,如果我评论exec行,它与print语句一起工作正常... 那么请你能告诉我我在哪里做错了吗?

1 个答案:

答案 0 :(得分:0)

你应该这样做,使用临时表而不是直接从sys.tables中选择

SELECT NAME into #temp FROM SYS.TABLES WHERE NAME LIKE 'AK_LIB_ADDRESS%'
DECLARE CURS_TABLE CURSOR FOR 
SELECT NAME from #temp 

DECLARE @TABLE_NAME VARCHAR(100);
DECLARE @SQL VARCHAR(300);
OPEN CURS_TABLE
FETCH NEXT FROM CURS_TABLE INTO @TABLE_NAME;

WHILE @@FETCH_STATUS = 0
BEGIN
    select  @TABLE_NAME
    SET @SQL = 'ALTER TABLE '+@TABLE_NAME+' ADD PRIMARY KEY(ID);';
    EXEC (@SQL)
    FETCH NEXT FROM CURS_TABLE INTO @TABLE_NAME
END

CLOSE CURS_TABLE;
DEALLOCATE CURS_TABLE;

或者向光标添加一个Insensitive关键字。原因是您正在将堆更改为触发器内的B树,这就是您在游标中获得不一致行为的原因。

DECLARE CURS_TABLE CURSOR INSENSITIVE FOR 
SELECT NAME FROM SYS.TABLES WHERE NAME LIKE 'AK_LIB_ADDRESS%'
DECLARE @TABLE_NAME VARCHAR(100);
DECLARE @SQL VARCHAR(300);