首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

与此同时清除多表中的数据

2013-06-25 
同时清除多表中的数据use testsql2create table hello(name varchar(100) not null)create table hello1(n

同时清除多表中的数据
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 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

Table后面加空格就可以了。
[解决办法]

引用:
 exec('truncate table     '+ @tablename)  这是在调用存储过程还是什么啊?

在执行动态拼接的SQL: truncate table [表名]

热点排行
Bad Request.