sql constraints

 

PRIMARY KEY constraint 

   primary key, as the name suggests, is the primary key, also known as the primary key. A row in a table is called a tuple. If there is an attribute or several attributes, its value can uniquely identify a row in the table, and such an attribute or attributes can be used as the primary key of the table.

 

FOREIGN KEY  

  Foreign key constraints are used to strengthen the connection between one or more columns of data in two tables (primary and secondary). The order in which foreign key constraints are created is to define the primary key of the primary table first, and then define the foreign key of the secondary table. That is to say, only the primary key of the primary table can be used by the secondary table as a foreign key, and the columns in the constrained secondary table may not be the primary key. The primary table restricts the operations of updating and inserting from the secondary table. 

 

-建库 if exists(select * from sys.sysdatabases where name='wf') begin use master drop database wf end go create database wf on (name=N'wf',filename=N'E:\MyCode\ETC收费站\ETC收费站\ETC_Data\wf.mdf',size=3mb,maxsize=unlimited,filegrowth=1)
--建库
if exists(select * from sys.sysdatabases where name='wf')
begin
use master
drop database wf
end
go
create database wf

on
(name=N'wf',filename=N'E:\MyCode\ETC toll booth\ETC toll booth\ETC_Data\wf.mdf',size=3mb,maxsize=unlimited,filegrowth=1)
log on
(name= N'wf',filename=N'E:\MyCode\ETC toll gate\ETC toll gate\ETC_Data\wf_log.ldf',size=3mb,maxsize=unlimited,filegrowth=1)
go
use wf
go
if exists(select * from sys.sysobjects where name='wf' )
begin
drop table wf
end --create


table, create constraint, relation
use wf 
go 
create table tableok 

col1 int, 
col2_notnull int not null, 
col3_default nchar(1) not null default(' Male'), --default male
col4_default datetime not null default(getdate()), --default get system time
col5_check int not null check(col5_check>=18 and col5_check<=55), -- add constraints, the data value is between 18 and 55
col6_check nchar(9) not null check(col6_check like 'msd0902[0-9][^ 6-9]'), --Add constraints, the first 7 digits of the data value must be 'msd0902', the last digit can be any number from 0-9, and the last digit is not a number between 6-9.
cola_primary nchar(5) not null primary key, -- establish primary key
colb_unique int unique, -- unique constraint
col7_Identity int not null identity(100,1), -- self-growth, starting from 100, each column value increases by 1
col8_identity numeric (5,0) not null identity(1,1) -- self-increase, starting from 1, each column value increases by 1, the maximum value is a 5-digit integer
col9_guid uniqueidentifier not null default(newid()) -- use newid () function, get column values ​​randomly

Create a database
  Determine whether the database exists before creating if exists (select * from sysdatabases where name='databaseName') drop database databaseName go Create DATABASE database-name
delete the database
  drop database dbname
backup sql server
  --- create device for backup data USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' --- start backup BACKUP DATABASE pubs TO testBack
create new table
  create create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) Create a new table based on an existing table: A: go use original database name go select * into destination database name.dbo. Destination table name from original table name (use old table to create new table) B: create table tab_new as select col1,col2… from tab_old definition only
create sequence
  create sequence SIMON_SEQUENCE minvalue 1 -- minimum value maxvalue 999999999999999999999999999 maximum value start with 1 start value Increment by 1 Add a few cache 20 each time;
delete the new table
  drop table tabname
add a column
  Alter table tabname add column col type Note: Columns cannot be deleted after they are added. The data type cannot be changed after the column is added in DB2. The only thing that can be changed is to increase the length of the varchar type.
Add primary key
  Alter table tabname add primary key(col) Description: Delete primary key: Alter table tabname drop primary key(col)
Create index
  create [unique] index idxname on tabname(col….) Delete index: drop index idxname on tabname Note: The index is immutable, if you want to change it, you must delete it and rebuild it.
Create view
  create view viewname as select statement Delete view: drop view viewname
A few simple basic SQL statements
  Select: select * from table1 where range insert: insert into table1(field1,field2) values(value1,value2) delete: delete from table1 where range update: update table1 set field1=value1 where range lookup: select * from table1 where field1 like '%value1%' (all strings that contain the pattern 'value1')---like syntax is very subtle, check the data! Sort: select * from table1 order by field1,field2 [desc] Total: select count(*) as totalcount from table1 Sum: select sum(field1) as sumvalue from table1 Average: select avg(field1) as avgvalue from table1 Maximum: select max(field1) as maxvalue from table1 Minimum: select min(field1) as minvalue from table1[ separator]
Several advanced query words
  A: UNION operator The UNION operator derives a result table by combining two other result tables (eg TABLE1 and TABLE2) and eliminating any duplicate rows in the tables. When ALL is used with UNION (ie UNION ALL), duplicate rows are not eliminated. In both cases, each row of the derived table is either from TABLE1 or TABLE2. B: EXCEPT operator The EXCEPT operator derives a result table by including all rows in TABLE1 but not in TABLE2 and eliminating all duplicate rows. When ALL is used with EXCEPT (EXCEPT ALL), duplicate rows are not eliminated. C: INTERSECT operator The INTERSECT operator derives a result table by including only the rows that are in both TABLE1 and TABLE2 and eliminating any duplicate rows. When ALL is used with INTERSECT (INTERSECT ALL), duplicate rows are not eliminated. Note: Several query result rows using operator words must be consistent.
Use outer join
  A, left outer join: Left outer join (left join): The result set includes both the matching rows of the join table and all the rows of the left join table. SQL: select aa, ab, ac, bc, bd, bf from a LEFT OUT JOIN b ON aa = bc B: right outer join: right outer join (right join): the result set includes both the matching join rows of the join table, and the Include all rows of the right join table. C: full outer join: Full outer join: includes not only the matching rows of the symbolic join table, but also all the records in the two join tables.
Edit this paragraph to determine whether the object exists to
determine whether the database exists
  if exists (select * from sys.databases where name = 'database name') drop database [database name]
determines whether the table exists
  if not exists (select * from sysobjects where [name] = 'table name' and xtype='U' ) begin -- create a table end here to
determine whether the stored procedure exists
  if exists (select * from sysobjects where id = object_id(N'[stored procedure name]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [ Stored procedure name]
Determine whether the temporary table exists
  if object_id('tempdb..#temporary table name') is not null drop table #Temporary table name
determines whether the view exists
  --SQL Server 2000 IF EXISTS (SELECT * FROM sysviews WHERE object_id = '[dbo].[view name]' --SQL Server 2005 IF EXISTS (SELECT * FROM sys.views WHERE object_id = '[dbo].[view name]'
to determine whether the function exists
  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[function name]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo ].[function name]
Get the object information created by the user
  SELECT [name],[id],crdate FROM sysobjects where xtype='U'   
Determine whether the column exists
  if exists(select * from syscolumns where id=object_id('table name' ) and name='column name') alter table table name drop column column name
determines whether the column is self-
  incrementing if columnproperty(object_id('table'),'col','IsIdentity')=1 print 'self-incrementing column' else print 'Not an auto-increment column' SELECT * FROM sys.columns WHERE object_id=OBJECT_ID('table name') AND is_identity=1
to determine whether there is an index in the table
  if exists(select * from sysindexes where id=object_id('table name') and name='index name') print 'exists' else print 'There is no
object in the view database
  SELECT * FROM sys.sysobjects WHERE name='object name'
Edit this paragraph to improve
Copy table
  (only copy structure, source table name: a new table name: b) (Access available) Method 1: select * into b from a where 1<>1 Method 2: select top 0 * into b from a
copy table
  ( Copy data, source table name: a Target table name: b) (Access available) insert into b(a, b, c) select d, e, f from b;
copy between tables across databases
  (use absolute path for specific data ) (Access available) insert into b(a, b, c) select d,e,f from b in 'specific database' where condition example: ..from b in '"&Server.MapPath("."&"\data .mdb" &"' where..
subquery
  (table name 1: a table name 2: b) select a,b,c from a where a IN (select d from b or: select a,b,c from a where a IN (1,2,3)
Display article, submitter and last reply time
  select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a. title) b
outer join query
  (table name 1: a table name 2: b) select aa, ab, ac, bc, bd, b.f from a LEFT OUT JOIN b ON a.a = b.c
Online view query
  (table name 1: a select * from (Select a,b,c FROM a) T where ta > 1;
usage of
  between The boundary value is included when limiting the range of query data, not between does not include select * from table1 where time between time1 and time2 select a,b,c, from table1 where a not between value1 and value2
in How to use
  select * from table1 where a [not] in ('value1','value2',' value 4', 'value 6')
delete the information that is not already in the secondary table in the main table
  Two associated tables delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1
Four-table joint query problem
  select * from a left inner join b on aa=bb right inner join c on aa=cc inner join d on aa=dd where .....
the schedule is reminded five minutes in advance
  SQL: select * from schedule where datediff('minute ',f start time, getdate())>5
a sql statement to get database paging
  select top 10 b.* from (select top 20 primary key field, sort field from table name order by sort field desc) a, table name b where b. primary key field = a. primary key field order by a.
first 10 records of sort field
  select top 10 * form table1 where range
selection ranking
  Select all the information of the largest record corresponding to a in each group of data with the same b value (a usage similar to this can be used for the monthly ranking list of the forum and the analysis of monthly hot-selling products , ranked by subject grades, etc.) select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
The derived result table
  includes all those in TableA but not in Rows in TableB and TableC and eliminate all duplicate rows to derive a result table (select a from tableA except (select a from tableB) except (select a from tableC)
randomly take out 10 data
  select top 10 * from tablename order by newid ()
Randomly select records
  select newid()
delete duplicate records
  Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
List all table names in the database
  select name from sysobjects where type='U'
lists all the tables in the table
  select name from syscolumns where id=object_id('TableName')
lists
  the type, vendor, and pcs fields, arranged by the type field, case can be convenient To achieve multiple selection, similar to the case in select. select type,sum(case vender when 'A' then pcs else 0 end),sum(case vender when 'C' then pcs else 0 end),sum(case vender when 'B' then pcs else 0 end) FROM tablename group Display the result by type: type vender pcs Computer A 1 Computer A 1 CD-ROM B 2 CD-ROM A 2 Mobile phone B 3 Mobile phone C 3
Initialization table table1
  TRUNCATE TABLE table1
select records from 10 to 15
  select top 5 * from (select top 15 * from table order by id asc) table_alias order by id desc
data type conversion
  declare @numid int declare @id varchar(50) set @numid=2005 set @id=convert(varchar,@numid) Through the above statement, the data type Int is converted to varchar
. The use of
1=1, 1=2 is used
  more in the combination of SQL statements. "where 1=1" means to select all "where 1=2" and not select all, such as: if @strWhere !=' begin set @strSQL = 'select count(*) as Total from [' + @tblName + '] where ' + @strWhere end else begin set @strSQL = 'select count(*) as Total from [' + @tblName + ']' end we Can be written directly as set @strSQL = 'select count(*) as Total from [' + @tblName + '] where 1=1 and '+ @strWhere
shrink database
  -- rebuild index DBCC REINDEX DBCC INDEXDEFRAG -- shrink data and log DBCC SHRINKDB DBCC SHRINKFILE
Compress the database
  dbcc shrinkdatabase(dbname) Transfer the database to a new user with existing user rights exec sp_change_users_login 'update_one','newname','oldname'   go
Check backup set
  RESTORE VERIFYONLY from disk='E:\dvbbs.bak'
Repair database
  Alter DATABASE [dvbbs] SET SINGLE_USER GO DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK GO Alter DATABASE [dvbbs] SET MULTI_USER GO
log clear
  SET NOCOUNT ON   DECLARE @LogicalFileName sysname,   @MaxMinutes INT,   @NewSize INT   USE tablename -- 要操作的数据库名   Select @LogicalFileName = 'tablename_log', -- 日志文件名   @MaxMinutes = 10, -- Limit on time allowed to wrap log.   @NewSize = 1 -- 你想设定的日志文件的大小(M)   -- Setup / initialize   DECLARE @OriginalSize int   Select @OriginalSize = size   FROM sysfiles   Where name = @LogicalFileName   Select 'Original Size of ' + db_name() + ' LOG is ' +   CONVERT(VARCHAR(30),@OriginalSize) + ' 8K pages or ' +   CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + 'MB'   FROM sysfiles   Where name = @LogicalFileName   Create TABLE DummyTrans   (DummyColumn char (8000) not null)   DECLARE @Counter INT,   @StartTime DATETIME,   @TruncLog VARCHAR(255)   Select @StartTime = GETDATE(),   @TruncLog = 'BACKUP LOG '+ db_name() + ' WITH TRUNCATE_ONLY'   DBCC SHRINKFILE (@LogicalFileName, @NewSize)   EXEC (@TruncLog)   -- Wrap the log if necessary.   WHILE @MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) -- time has not expired   AND @OriginalSize = (Select size FROM sysfiles Where name = @LogicalFileName)   AND (@OriginalSize * 8 /1024) > @NewSize   BEGIN -- Outer loop.   Select @Counter = 0   WHILE ((@Counter < @OriginalSize / 16) AND (@Counter < 50000))   BEGIN -- update   Insert DummyTrans VALUES ('Fill Log')   Delete DummyTrans   Select @Counter = @Counter + 1   END   EXEC (@TruncLog)   END   Select 'Final Size of ' + db_name() + ' LOG is ' +   CONVERT(VARCHAR(30),size) + ' 8K pages or ' +   CONVERT(VARCHAR(30),(size*8/1024)) + 'MB'  FROM sysfiles   Where name = @LogicalFileName   Drop TABLE DummyTrans   SET NOCOUNT OFF
更改某个表
  exec sp_changeobjectowner 'tablename','dbo'
存储更改全部表
  Create PROCEDURE dbo.User_ChangeObjectOwnerBatch   @OldOwner as NVARCHAR(128),   @NewOwner as NVARCHAR(128)   AS   DECLARE @Name as NVARCHAR(128)   DECLARE @Owner as NVARCHAR(128)   DECLARE @OwnerName as NVARCHAR(128)   DECLARE curObject CURSOR FOR   select 'Name' = name,   'Owner' = user_name(uid)   from sysobjects   where user_name(uid)=@OldOwner   order by name   OPEN curObject   FETCH NEXT FROM curObject INTO @Name, @Owner   WHILE(@@FETCH_STATUS=0)   BEGIN   if @Owner=@OldOwner   begin   set @OwnerName = @OldOwner + '.' + rtrim(@Name)   exec sp_changeobjectowner @OwnerName, @NewOwner   end   -- select @name,@NewOwner,@OldOwner   FETCH NEXT FROM curObject INTO @Name,@Owner   END   close curObject   deallocate curObject   GO
Write data directly in a loop in SQL SERVER
  declare @i int set @i=1 while @i<30 begin insert into test (userid) values(@i) set @i=@i+1 end
--alter 
-- outside main key/reference/relationship constraint 
alter table slave table name [with check]--enable with nocheck--disable constraint 
add constraint FK_master table name_slave table name 
foreign key (field name in slave table) references master table name ( field name in the main table)

--Other non-primary foreign key constraints 
alter table wf 
add constraint constraint name constraint type specific constraint description

alter table wf--modify the joint primary key 
add constraint Pk_cola_primary primary key(cola_primary,col1)


---1.insert [into] <table name>[column name] values ​​<value list>  --1
) All [column names] can be omitted 
insert stuinfo values('','','')

create table outtable 

id int not null primary key, 
[name] nvarchar(4) not null, 
adrress nvarchar(20) default '地址不详' 

truncate table outtable 
alter table outtable alter column id int identity(4,1) 
insert outtable values (1,22,'') 
insert outtable values(2,32,'') 
insert outtable values(3,33,'') 
--2)部分 
insert stuinfo (stuno) values ('') 
--3)自动增长列,不能手动插入。将列名、列值省略

---2多行插入 
---1)从一个现有表中取出所取字段插入到目标表中 
insert into stuinfo (stuno,stuname) select stuno,stuname from stumarks 
insert into stuinfo(stuno) select stuno from stumarks

---2)从现有的表中取出数据,创建一个新表,将数据插入到新表中 
select [列名] into <表名> from <源表名> 
select id as '编号',[name] into newtable from outtable 
select cast(id as varchar(4))+cast([name] as nvarchar(4)) as '编号及姓名' ,id into newtable from outtable 
select * from newtable 
drop table newtable

---3)union 现有的多个表中取数据放入现有的表3中 
insert into<表名3> [列名] 
select * from 表1 union 
select * from 表2

--3.更新语句 update <表名> set <列名=更新值> [where <更新条件>] 
---注意:一般where不要省略,如不写将修改整个表

--4truncate删除数据 
--比delete只能全部删除数据,不能部分删除,删除的效率高,可以重置自增长列

select * from stumarks 
select * from stuinfos

--给考试成绩各提5分,100分封顶。 
update stumarks set writtenexam=100 
where writtenexam>95 
update stumarks set labexam=100 
where labexam>95

update stumarks 
set writtenexam=writtenexam+5 
where writtenexam+5<=100

update stumarks 
set labexam=labexam+5 
where labexam+5<=100

 

select examno,stuno,writtenexam+5 as 笔试,labexam+5 as 机试 from stumarks where writtenexam+5<=100 and labexam+5<=100

create table t 

id int , 
name nchar(4), 
dt datetime, 
age int, 
score int 
)

insert t values (1,'a',getdate(),20,50) 
insert t values (2,'b',getdate(),21,60) 
insert t values (3,'c',getdate(),21,100) 
insert t values (4,'d',getdate(),23,80)

select * from t 
select top 2 * from t 
select top 60 percent * from t

select top 5 * from products 
select top 5 percent * from products

--启别名:两种方式 As(可省略)、= 
select productid as '编号' from products 
select productid '编号' from products 
select '编号'=productid from products   
select employeeid from employees 
--declare @a nvarchar(6) 
--set @a='员工编号为:' 
select N'员工编号为:'+cast(employeeid as nvarchar(2)) from employees

select distinct country from suppliers order by country 
select * from t 
select * from products 
select * from products order by 4 asc,6 desc 
select * from products where unitprice>16 and productname like 'T%' or productid=16

select * from suppliers where country in('japan','italy') 
(1)char、varchar、text和nchar、nvarchar、ntext
        char和varchar的长度都在1到8000之间,它们的区别在于char是定长字符数据,而varchar是变长字符数据。所谓定长就是长度固定的,当输入的数据长度没有达到指定的长度时将自动以英文空格在其后面填充,使长度达到相应的长度;而变长字符数据则不会以空格填充。text存储可变长度的非Unicode数据,最大长度为2^31-1(2,147,483,647)个字符。
       后面三种数据类型和前面的相比,从名称上看只是多了个字母"n",它表示存储的是Unicode数据类型的字符。写过程序的朋友对Unicode应该很了解。字符中,英文字符只需要一个字节存储就足够了,但汉字众多,需要两个字节存储,英文与汉字同时存在时容易造成混乱,Unicode字符集就是为了解决字符集这种不兼容的问题而产生的,它所有的字符都用两个字节表示,即英文字符也是用两个字节表示。nchar、nvarchar的长度是在1到4000之间。和char、varchar比较:nchar、nvarchar则最多存储4000个字符,不论是英文还是汉字;而char、varchar最多能存储8000个英文,4000个汉字。可以看出使用nchar、nvarchar数据类型时不用担心输入的字符是英文还是汉字,较为方便,但在存储英文时数量上有些损失。
(2)datetime和smalldatetime
datetime:从1753年1月1日到9999年12月31日的日期和时间数据,精确到百分之三秒。
smalldatetime:从1900年1月1日到2079年6月6日的日期和时间数据,精确到分钟。
(3)bitint、int、smallint、tinyint和bit
bigint:从-2^63(-9223372036854775808)到2^63-1(9223372036854775807)的整型数据。
int:从-2^31(-2,147,483,648)到2^31-1(2,147,483,647)的整型数据。
smallint:从-2^15(-32,768)到2^15-1(32,767)的整数数据。
tinyint:从0到255的整数数据。
bit:1或0的整数数据。
(4)decimal和numeric
这两种数据类型是等效的。都有两个参数:p(精度)和s(小数位数)。p指定小数点左边和右边可以存储的十进制数字的最大个数,p必须是从 1到38之间的值。s指定小数点右边可以存储的十进制数字的最大个数,s必须是从0到p之间的值,默认小数位数是0。
(5)float和real
float:从-1.79^308到1.79^308之间的浮点数字数据。
real:从-3.40^38到3.40^38之间的浮点数字数据。在SQL Server中,real的同义词为float(24)。

SELECT --从数据库表中检索数据行和列 
  select col1,col2,col3.....from table
INSERT --向数据库表添加新数据行 
      insert into table(col1,col2....) values(value1,value2...)
      insert into table(col1,col2....) select col1,col2...from table
DELETE --从数据库表中删除数据行 
      delete from table 
UPDATE --更新数据库表中的数据 
      update table set col1=value,......
--数据定义 
CREATE TABLE --创建一个数据库表 
create table tbame (col1 int,col2 char(20))
DROP TABLE --从数据库中删除表 
drop table tbname
ALTER TABLE --修改数据库表结构 
--增加列
      alter table #a add col3 int
--删除列
       alter table #a drop column col3
--增加列的默认值
alter   table   tbname   add   CONSTRAINT   tf_name   default   'a'   for   col2 CREATE VIEW --创建一个视图   
      create view view_name as
         select * from tbname  where ....
DROP VIEW --从数据库中删除视图     
drop view view_nameCREATE INDEX --为数据库表创建一个索引    
--创建简单的非聚集索引    CREATE INDEX index_name        ON tbname (VendorID);    
--创建简单的唯一非聚集索引
    CREATE UNIQUE INDEX index_name
        ON tbname (VendorID);
DROP INDEX --从数据库中删除索引 
     drop index index_name on tbnameCREATE PROCEDURE --创建一个存储过程 
   create procedure name as
    begin
    ......
    end
DROP PROCEDURE --从数据库中删除存储过程 
   drop procedure nameCREATE TRIGGER --创建一个触发器 
create trigger name on tbname 
       FOR INSERT,UPDATE     AS 
       .......
DROP TRIGGER --从数据库中删除触发器

 
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326948023&siteId=291194637