常用sql语句

1.两张结构相同的表 导入数据

insert into tableA (字段1,字段2,字段3) 
select 字段1,字段2,字段3 from tableB

2.触发器加判断条件

USE [dbname]
GO
/****** Object:  Trigger [dbo].[[tri_table]]    Script Date: 2019/4/25 11:25:27 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[tri_table]
   ON  [dbo].TableB
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
	--新增
    if(exists(select 1 from inserted) and not exists(select 1 from deleted))
		begin 
            declare @RoleID int--根据部门设置角色
            IF EXISTS(SELECT 1 FROM inserted WHERE ORG_NAME='部门A')
				set @RoleID=1
            ELSE IF EXISTS(SELECT 1 FROM inserted WHERE ORG_NAME='部门B')
				set @RoleID=2
			insert into TableA(字段1,字段2,部门,角色编号)
			select inserted.字段1,inserted.字段2,inserted.部门,@RoleID from inserted
		end
	--删除
    if(not exists(select 1 from inserted) and exists(select 1 from deleted))
		begin
			delete TableA from TableA u,
			deleted d where u.Account=d.Account
		end
	--更新
    if(exists(select 1 from inserted) and exists(select 1 from deleted))
		begin
			update TableA set  字段1=i.字段1,字段2=i.字段2
			from inserted i where TableA.Account=i.Account
		end
END

3.自增列重新从x开始

dbcc checkident(TableName,reseed,x)--x为任意

4.多行记录拼成1行并用 “  ,” 隔开

select val=stuff( 
    (select ','+ pgNAME from ActInfo as b where b.ActivityID = a.ActivityID and  b.ActivityID=1 for xml path('')),1,1,'')
from ActInfo as a where a.ActivityID = 1  group by ActivityID


id  pgNAME   ->>>    val
1   张三              张三,李四,王五
1   李四
1   王五

5.查询所有表包含某个字段的sql

SELECT DISTINCT
t.table_name,
c.COLUMN_NAME,
t.TABLE_TYPE
FROM
information_schema.TABLES t
INNER JOIN information_schema.COLUMNS c
ON c.TABLE_NAME = t.TABLE_NAME
where c.COLUMN_NAME = 'CityID'  --是否包含CityID字段
ORDER BY t.TABLE_TYPE

6.查询某张表是否被存储过程或者视图使用

select distinct object_name(id) from syscomments 
where id in (select id from sysobjects where type in('V','P')) --V表示视图,P表示存储过程
and text like '%tablename%'--tablename为需要查询被引用的表名称

7.批量插入测试数据(主从表)

declare @i int
set @i=1
while @i<101
begin
	--主表
    insert into table_name1(a,b,c,d,e,f,g,h,i)
    values('字段a','字段b','字段c','字段d','字段e','字段f','字段g','字段h','字段i')
	--从表1
    --(select ident_current('table_name1')) 获取主表的自增主键
    --添加从表,从表测试数据来源从表数据,条件为a=1
	insert into table_name2(a,b,c,d)
	select (select ident_current('table_name1')),b,c,d from table_name2 where a=1
	--从表2
	insert into table_name3(a,b,c)
	select (select ident_current('table_name1')),b,c from table_name3 where a=1
	set @i=@i+1
end 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值