复制表
- 方法一:
这存储过程主要是用来复制或者备份表、表数据
输入被复制的表的名称
输入要复制的名称
是否复制表中的数据
/**
*dk 用来复制表和表数据
*还有一些功能没有完善,复制索引、列说明
**/
alter proc CopyTable
@tables varchar(1000),--要复制的表
@tablesCopy varchar(1000),--要复制的表名
@tablesData varchar(1000)='true'--默认复制数据
as
begin
--去两边的空格
set @tablesCopy=ltrim(rtrim(@tablesCopy))
--声明可用变量
declare @tablesName varchar(1000),@tablesCopyName varchar(1000),@tablesId int,
@sql varchar(1000),@name varchar(1000)
--查询数据库名称和id
select @tablesName=name,@tablesId=id from sysobjects where name=@tables
select @tablesCopyName=name from sysobjects where name=@tablesCopy
if isnull(@tablesName,null)<>@tablesName
begin
print '输入的表名为空或不存在'
return
end
if isnull(@tablesCopyName,null)=@tablesCopyName
begin
print '被复制的表名已存在'
return
end
else
begin
--创建表
set @sql='create table '+@tablesCopy+'(a int)'
exec(@sql)
end
--添加列
declare @tablesType varchar(1000),@Type varchar(1000),@length int,
@tablesValue varchar(1000),@leftSym varchar(100),@reghtSym varchar(100),
@tableslie varchar(1000)='true'
declare sys_name cursor
for(
--查询出列名的数据类型
select a.COLUMN_NAME,a.DATA_TYPE,a.CHARACTER_MAXIMUM_LENGTH--,b.value
from information_schema.COLUMNS as a left join sys.extended_properties as b
on a.TABLE_NAME=OBJECT_NAME(b.major_id) and a.ORDINAL_POSITION=b.minor_id
where a.TABLE_NAME=@tables)
open sys_name
--循环下一行游标
fetch next from sys_name into @name,@Type,@length
while @@FETCH_STATUS=0
begin try
if isnull(@length,0)<>0
begin
set @tablesType=' '+@Type+'('+cast(@length as varchar)+')'
end
--如果类型为money和decimal统一使用'decimal(18,2)'
else if isnull(@Type,null)='money' or isnull(@Type,null)='decimal'
begin
set @tablesType=' decimal(18,2)'
end
--时间戳类型比较特殊,因为它不能被复制,比较唯一,所以转换成bigint
else if isnull(@Type,null)='timestamp'
begin
set @tablesType=' bigint'
end
else
begin
set @tablesType=' '+@Type
end
--添加列
if @tableslie='true'
begin
set @sql='alter table '+@tablesCopy+' add ' +@name+ @tablesType
exec(@sql)
end
set @tableslie='true'
fetch next from sys_name into @name,@Type,@length
end try
--出现异常删除复制表
begin catch
set @tablesValue='异常信息:'+ERROR_MESSAGE()
print @tablesValue
set @sql ='drop table '+@tablesCopy
exec(@sql)
return
end catch
close sys_name
deallocate sys_name
--删除之前的列
set @sql='ALTER TABLE '+@tablesCopy+' DROP COLUMN a'
exec(@sql)
--添加数据
if isnull(@tablesData,null)='true'
begin try
set @sql='insert into '+@tablesCopy+' select * from '+@tables
exec(@sql)
end try
--出现异常删除复制表
begin catch
set @tablesValue='异常信息:'+ERROR_MESSAGE()
print @tablesValue
set @sql ='drop table '+@tablesCopy
exec(@sql)
return
end catch
end
- 方法二:
其实还有一个更加简单的方法:
tables是复制表,tablesCopy是被复制表
where 1=2是不复制数据,想要复制数据去掉where条件就好了
select * into tablesCopy from tables where 1=2
- 方法三:
想要复制的更详细,什么东西都不想遗漏
1、在tables表上按右键,选择“编写表脚本为”=》Create
2、然后在这个结构基础上把tables改成tablesCopy就行了1
注脚的解释要在设置里选择编写索引脚本 ↩︎