SQL Server常用sql详解

(1)通过sqlcmd,连接SQL Server数据库

sqlcmd -S localhost -U SA -P 'sqlserver@123'

(2)数据库操作
-- 查询数据库列表
select * from SysDatabases;
go

-- 创建数据库
create database testdb;
use testdb;
go
(3)数据表操作
-- 查询数据表列表
select * from sysobjects where xtype = 'u';
go

-- 创建数据表
create table sys_user (id varchar(200),user_name varchar(200));
go

-- 添加表描述
execute sp_addextendedproperty 'MS_Description','yonghubiao','user','dbo','table','sys_user',null,null;
go

-- 删除表描述
execute sp_dropextendedproperty 'MS_Description','user','dbo','table','sys_user',null,null; 
go

-- 添加字段描述
execute sp_addextendedproperty 'MS_Description','用户ID','user','dbo','table','sys_user','column','id';
execute sp_addextendedproperty 'MS_Description','用户名称','user','dbo','table','sys_user','column','user_name';
go

-- 修改字段描述
execute sp_updateextendedproperty 'MS_Description','user-id','user','dbo','table','sys_user','column','id';
execute sp_updateextendedproperty 'MS_Description','user-name','user','dbo','table','sys_user','column','user_name';
go

-- 查询表结构
EXEC sp_help 'sys_user';
go
(4)SELECT操作
-- 插入数据
insert sys_user values('A001','JACK');
insert sys_user values('A002','SQLSERVER');
insert sys_user values('A003','MYSQL');
go

-- 查询所有数据
select * from sys_user;
go

-- 查询表名,列名
select a.Name as table_name,b.Name as column_name 
from Sys.tables a 
inner join Sys.columns b on a.object_id=b.object_id ;
go

-- 查询表名,表描述
select a.name,CONVERT(NVARCHAR(100),isnull(g.[value],'-')) as table_comment 
from  Sys.tables a 
left join sys.extended_properties g on (a.object_id = g.major_id AND g.minor_id = 0);
go

-- 查询表名,列名,列描述
select a.Name as table_name,b.Name as column_name,
CONVERT(NVARCHAR(100),isnull(g.[value],'-')) as comments 
from Sys.tables a 
inner join Sys.columns b on a.object_id=b.object_id 
left join Sys.extended_properties g on (b.object_id = g.major_id 
AND g.minor_id = b.column_id);
go

你可能感兴趣的:(SQL Server常用sql详解)