日期:2014-05-17  浏览次数:20432 次

同时清除多表中的数据
use testsql2
create table hello(name varchar(100) not null)
create table hello1(name varchar(100) not null)
create table hello2(name varchar(100) not null)
create table hello4(name varchar(100) not null)
create table hello3(name varchar(100) not null)
create table hello5(name varchar(100) not null)
go


declare tables_cursor cursor
for
  SELECT name FROM sysobjects WHERE type = 'U'
open tables_cursor
declare @tablename sysname
fetch next from tables_cursor into @tablename
while(@@fetch_status<>-1)
begin
--truncate table @tablename
exec('truncate table'+ @tablename)
fetch next from tables_cursor into @tablename
end

为什么我运行上面的代码后会报下面的错误啊?是哪里出错了?有没有更好的办法?

消息 102,级别 15,状态 1,第 1 行
'tablehello5' 附近有语法错误。
消息 102,级别 15,状态 1,第 1 行
'tablehello' 附近有语法错误。
消息 102,级别 15,状态 1,第 1 行
'tablehello1' 附近有语法错误。
消息 102,级别 15,状态 1,第 1 行
'tablehello2' 附近有语法错误。
消息 102,级别 15,状态 1,第 1 行
'tablehello4' 附近有语法错误。
消息 102,级别 15,状态 1,第 1 行
'tablehello3' 附近有语法错误。
Cursor 行业数据

------解决方案--------------------
declare tables_cursor cursor
for
  SELECT name FROM sysobjects WHERE type = 'U'
open tables_cursor
declare @tablename sysname
fetch next from tables_cursor into @tablename
while(@@fetch_status<>-1)
begin
--truncate table @tablename
exec('truncate table加个空格 '+ @tablename)
fetch next from tables_cursor into @tablename
end


------解决方案--------------------
另外如果是2005以上版本SELECT name FROM sysobjects WHERE type = 'U'
可以换成select name from sys.tables 即可
------解决方案--------------------
truncate命令少了空格..

declare tables_cursor cursor
for
  SELECT name FROM sysobjects WHERE type = 'U'
  
open tables_cursor
declare @tablename sysname

fetch next from tables_cursor into @tablename
while(@@fetch_status<>-1)
begin
--truncate table @tablename
exec('truncate table '+ @tablename)
fetch next from tables_cursor into @tablename
end

close tables_cursor
deallocate tables_cursor

------解决方案--------------------
create table hello(name varchar(100) not null)
 create table hello1(name&n