SQL笔记 [长期更新] (-2015.4)

【遍历所有表,复制表结构,复制表数据】

--插入语句
SELECT * INTO A FROM B 是在还没有A表的情况下,直接通过B表创建并把B表数据复制到A表里面,之后A,B表的结构和数据完全一样。
insert into A select * from B 是在已经创建了A表的情况下,将B表数据复制到A表,此前A表的结构要和B表相同,不然插入的时候报错。

--复制表结构到新的库中
SELECT * INTO table1 FROM DBTest.dbo.table1



--查询库中的所有表名
SELECT * FROM sysobjects WHERE xtype='U'
--SELECT * FROM sys.objects WHERE type='U'



--遍历库中的所有表,对所有表批量执行指定sql
declare @tb_name nvarchar(100)
declare @i int
declare @tb table(id int identity(1,1),name nvarchar(1000))

set @i = 1
set @tb_name = 'cx' --以这个值开头的所有表

insert into @tb(name)
select t.name
from sysobjects t
where xtype='u' and t.name like @tb_name+'%'

while @i <= (select COUNT(*) from @tb)
begin
select @tb_name = name from @tb where id = @i;

exec('select * from '+@tb_name);

set @i = @i + 1
end
 
SQL设置千分位:
select convert(varchar,cast(asst_depreciation_money AS MONEY),1) AS asst_depreciation_money -----带小数点的
select reverse(stuff(reverse(convert(varchar,convert(money,123000),1)),1,3,'')) ----不带小数点的

原文地址:https://www.cnblogs.com/jx270/p/4430198.html