using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using System.Reflection;
namespace DatableToList
{
class ConvertHelper<T> where T : new()
{
/// <summary>
/// 利用反射和泛型
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertToList(DataTable dt)
{
// 定义集合
List<T> ts = new List<T>();
// 获得此模型的类型
Type type = typeof(T);
//定义一个临时变量
string tempName = string.Empty;
//遍历DataTable中所有的数据行
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
//遍历该对象的所有属性
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name;//将属性名称赋值给临时变量
//检查DataTable是否包含此列(列名==对象的属性名)
if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;//该属性不可写,直接跳出
//取值
object value = dr[tempName];
//如果非空,则赋给对象的属性
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
//对象添加到泛型集合中
ts.Add(t);
}
return ts;
}
}
}
1.创建存储过程
CREATE PROCEDURE [dbo].[sp_generate_insert_script]
(
@table_name NVARCHAR(128), --表名
@condition NVARCHAR(128) --查询条件WHERE 语句
)
AS
DECLARE @column_list varchar(8000)
DECLARE @values_list varchar(8000)
DECLARE @sql varchar(8000)
DECLARE @msg varchar(8000)
CREATE TABLE #result(sql varchar(8000))
IF EXISTS(SELECT 1 FROM sysobjects WHERE xtype='U' AND name=@table_name)
BEGIN
SELECT @column_list='',@values_list=''
SELECT
@column_list=@column_list+','+name,
@values_list=@values_list+'+'',''+'+
CASE WHEN xtype IN(175,167,36) THEN--char,varchar,uniqueidentifier
'ISNULL(''''''''+REPLACE('+name+','''''''','''''''''''')+'''''''',''NULL'')'
WHEN xtype in(239,231) THEN--nchar,nvarchar
'ISNULL(''N''''''+REPLACE('+name+','''''''','''''''''''')+'''''''',''NULL'')'
WHEN xtype in(61,58) THEN--datetime,smalldatetime
'ISNULL(''''''''+CONVERT(char(23),'+name+',121)+'''''''',''NULL'')'
ELSE--digital
'ISNULL(CONVERT(varchar(20),'+name+'),''NULL'')'
END
FROM (SELECT a.name,a.xtype
FROM syscolumns a,sysobjects b
WHERE b.xtype='U' AND b.name=@table_name AND a.id=b.id
AND a.xtype NOT IN(173,165,34,35,99,98,189)
--NOT binary,varbinary,image,text,ntext,sql_variant,timestamp
)t
SELECT @column_list=STUFF(@column_list,1,1,''),
@values_list=STUFF(@values_list,1,4,''),
@sql='SELECT ''INSERT INTO '+@table_name+'('+@column_list+')'
+' VALUES('''+@values_list+'+'')'' sql FROM ['+@table_name+'] '
+ @condition;
INSERT INTO #result(sql)
EXEC(@sql)
END
ELSE
BEGIN
SET @msg='Can''t generate the insert script of the table '''+@table_name
+''', because it does not exist in the system catalog.'
DROP TABLE #result
RAISERROR(@msg,16,1)
RETURN
END
2.执行存储过程
DECLARE @table_name nvarchar(128)
DECLARE @condition nvarchar(128)
-- TODO: 在此处设置参数值。
SET @table_name='TableName' --表名称
SET @condition='WHERE 1=1' --筛选条件,如果筛选条件为空,SET @condition=''即可
EXECUTE [dbo].[sp_generate_insert_script]
@table_name
,@condition
1.首先添加一个类StopAppDomainRestartOnFolderDelete.cs
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace MyWebsite
{
public class StopAppDomainRestartOnFolderDeleteModule : IHttpModule
{
public void Init(HttpApplication context)
{
PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
object o = p.GetValue(null, null);
FieldInfo f = o.GetType().GetField("_dirMonSubdirs", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
object monitor = f.GetValue(o);
MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", BindingFlags.Instance | BindingFlags.NonPublic);
m.Invoke(monitor, new object[] { });
}
public void Dispose() { }
}
}
2.修改web.config文件
在<httpModules>节点中添加 <add name="stopAppDomainRestartOnFolderDelete" type="MyWebsite.StopAppDomainRestartOnFolderDeleteModule" />
。stopAppDomainRestartOnFolderDelete 自定义名称 建议与类名相同
。MyWebsite.StopAppDomainRestartOnFolderDeleteModule StopAppDomainRestartOnFolderDelete.cs 命名空间.类名称
--================================================
-- 触发器
--================================================
/*
*如何创建After DML触发器
*如何创建Instead Of DML触发器
*如何创建DDL触发器
*如何修改和删除既有触发器
*如何启用和禁用触发器
*如何限制触发器嵌套、设置触发器顺序和控制递归
*如何查看触发器元素据
*/
--1、DML触发器
--A、After DML触发器是在对表的insert,update和delete修改操作成功完成后执行
--语法:
/*
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)
CREATE TRIGGER [ schema_name . ]trigger_name
ON { table | view }
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME <method specifier [ ; ] > }
<dml_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
*/
--使用触发器来跟踪Production.ProductInventory表的行的插入和删除
--跟踪所有的插入、更新和删除操作
create table Production.ProductInventoryAudit
(
ProductID int not null,
LocationID smallint not null,
Shelf nvarchar(10) not null,
Bin tinyint not null,
Quantity smallint not null,
rowguid uniqueidentifier not null,
ModifiedDate datetime not null,
InsOrUPD char(1) not null
)
go
--创建触发器来填充Production.ProductInventoryAudit表
create trigger Production.trg_uid_ProductInventoryAudit
on Production.ProductInventory
after insert,delete
as
set nocount on --屏蔽触发器触发时"受影响行数"消息返回给调用的应用程序
--插入行
insert Production.ProductInventoryAudit
(ProductID,LocationID,Shelf,Bin,Quantity,rowguid,ModifiedDate,InsOrUPD)
select Distinct i.productID,i.LocationID,i.Shelf,i.Bin,i.Quantity,i.rowguid,getdate(),'I'
from inserted i
--删除的行
insert Production.ProductInventoryAudit
(ProductID,LocationID,Shelf,Bin,Quantity,rowguid,ModifiedDate,InsOrUPD)
select Distinct d.productID,d.LocationID,d.Shelf,d.Bin,d.Quantity,d.rowguid,getdate(),'D'
from deleted d
go
--插入一个新行
insert production.ProductInventory
(ProductID,LocationID,Shelf,Bin,Quantity) values(316,6,'A',4,22)
--删除一行
delete Production.ProductInventory where ProductID=316 and LocationID=6
--检测审核表
select ProductID,LocationID,InsOrUPD from Production.ProductInventoryAudit
--select * from production.ProductInventory
--select * from Production.Product
--B、创建Instead of DML触发器
--Instead of触发器的执行替代触发触发器的原始数据修改操作,并对表和视图都允许
--通常用于处理不允许进行数据修改的视图的数据修改操作
--示例:创建一个新表来保存HumanResources.Department表"等待批准pending approval"
--行。这些是需要经理的批准才能加入正式表的新部门。创建一个视图来显示来呢两个表中所有
--"已批准"和"等待批准"的部门,然后会在视图上创建一个Instead of触发器,导致插入的行
--会被转到新的审批表,而不是HumanResources.Department表:
--创建部门"审批"表
create table HumanResources.DepartmentApproval
(
Name nvarchar(50) not null unique,
GroupName nvarchar(50) not null,
ModifiedDate datetime not null default getdate()
)
go
--创建视图来查看已批准的和待批准的部门
create view HumanResources.vw_Department
as
select Name,GroupName,ModifiedDate,'Approved' Status
from HumanResources.Department
union
select Name,GroupName,ModifiedDate,'Pending Approval' Stuatus
from HumanResources.DepartmentApproval
go
--在新视图上创建Instead of触发器
create Trigger HumanResources.trg_vw_Department
on HumanResources.vw_Department
instead of insert
as
set nocount on
insert HumanResources.DepartmentApproval(Name,GroupName)
select i.Name,i.GroupName from inserted i
where i.Name not in(select Name from HumanResources.DepartmentApproval)
go
--向视图插入行
insert HumanResources.vw_Department
(Name,GroupName) values('Print Production','Manufacturing')
--检查视图的内容
select Status,Name
from HumanResources.vw_Department where GroupName='Manufacturing'
--select * from HumanResources.Department
--select * from HumanResources.DepartmentApproval
--C、使用DML触发器和事务
alter trigger Production.trg_uid_ProductInventoryAudit1
on Production.ProductInventory after insert,delete
as
set nocount on
if exists(select Shelf from inserted where Shelf='A')
begin
print 'Shelf ''A'' is closed for new inventory.'
rollback
end
--插入的行
insert Production.ProductInventoryAudit
(ProductID,LocationID,Shelf,Bin,Quantity,rowguid,ModifiedDate,InsOrUPD)
select distinct i.ProductID,i.LocationID,i.Shelf,i.Bin,i.Quantity,i.rowguid,getdate(),'I'
from inserted i
--删除的行
insert Production.ProductInventoryAudit
(
ProductID,LocationID,Shelf,Bin,Quantity,rowguid,ModifiedDate,InsOrUPD
)
select d.ProductID,d.LocationID,d.Shelf,d.Bin,d.Quantity,d.rowguid,getdate(),'D'
from deleted d
if exists
(
select Quantity from deleted where Quantity>0
)
begin
print '你不能删除有确定数量的行!'
rollback
end
go
--使用Shelf'A'插入新行来测试
insert Production.ProductInventory(ProductID,LocationID,Shelf,Bin,Quantity)
values(316,6,'A',4,22)
--使用显式事务演示两个删除
begin transaction
--删除0数量的行
delete Production.ProductInventory where ProductID=853 and LocationID=7
--删除非0数量的行
delete Production.ProductInventory where ProductID=999 and LocationID=60
commit transaction
--因为触发器发起了回滚,所以外部事务也结束了,所以同一事务中行没有被删除
select ProductID,LocationID from Production.ProductInventory
where (ProductID=853 and LocationID=7) or (ProductID=999 and LocationID=60)
--D、查看DML触发器的元数据
--演示查看当前数据库中有关触发器的信息
select object_name(parent_id) Table_or_ViewNM,
name TriggerNM,is_instead_of_trigger,is_disabled
from sys.triggers
where parent_class_desc='Object_or_column'
order by object_name(parent_id),name
--显示某个触发器的T-SQL定义,可以查询sys.sql_modules
select o.name,m.definition
from sys.sql_modules m
inner join sys.objects o
on m.object_id=o.object_id where o.type='TR'
--2、DDL触发器
--SQL Server2005引入DDL触发器是对服务器活数据库事件做出响应,而不是表数据
--修改
--语法:
/*
Trigger on a CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS statement (DDL Trigger)
CREATE TRIGGER trigger_name
ON { ALL SERVER | DATABASE }
[ WITH <ddl_trigger_option> [ ,...n ] ]
{ FOR | AFTER } { event_type | event_group } [ ,...n ]
AS { sql_statement [ ; ] [ ...n ] | EXTERNAL NAME < method specifier > [ ; ] }
<ddl_trigger_option> ::=
[ ENCRYPTION ]
[ EXECUTE AS Clause ]
<method_specifier> ::=
assembly_name.class_name.method_name
*/
--A、创建审核服务器级别的事件的DDL触发器
--创建DDL触发器
use master
go
--不允许在SQL实例上有新的登录
create trigger srv_trg_RestricNewLogins on all server
for create_login
as
print '禁止创建新登录'
rollback
go
--试图增加新的SQL登录:
create Login Joes with password='A235921'
go
--B、创建审核数据库级别的事件的DDL触发器
--创建审核表
create table dbo.ChangeAttempt
(
EventData xml not null,
AttemptDate datetime not null default getdate(),
DBUser char(50) not null
)
go
--创建一个数据库DDL触发器来跟踪索引操作,插入事件数据到新创建的表中:
create trigger db_trg_RestrictIndexChanges
on database
for create_index,alter_index,drop_index
as
set nocount on
--EVENTDATA()函数以XML格式返回服务器和数据事件信息
insert dbo.ChangeAttempt(EventData,DBUser) values(EVENTDATA(),User)
go
--在数据库中建立真实的索引
create nonclustered index in_ChangeAttempt_DBUser on dbo.ChangeAttempt(DBUser)
go
select * from dbo.ChangeAttempt
--C、查看DDL触发器元数据
--显示当前数据库中的DDL触发器
select name TriggerNM,is_disabled
from sys.triggers
where parent_class_desc='DATABASE'
order by object_name(parent_id),name
--查询服务器级别触发器数据
select name,s.type_desc SQL_or_CLR,
is_disabled,e.type_desc FiringEvents
From sys.server_triggers s
inner join sys.server_trigger_events e on
s.object_id=e.object_id
--查询数据库范围的DDL触发器的T-SQL定义
select t.name,m.Definition
from sys.triggers as t
inner join sys.sql_modules m on t.object_id=m.object_id
where t.parent_class_desc='database'
--要显示服务期范围内的DDL触发器
select t.name,m.definition
from sys.server_sql_modules m
inner join sys.server_triggers t on
m.object_id=t.object_id
--3、管理触发器
--修改触发器
--修改触发器,这次不会限制用户创建新的登录名,而是允许登录名事件,之后是一条警告和对审核表进行insert
alter trigger srv_trg_RestricNewLogins
on all server
for create_login
as
set nocount on
print '你创建登录将被监视'
insert AdventureWorks.dbo.ChangeAttempt
(EventData,DBUser) values(EVENTDATA(),user)
go
--启用和禁止触发器
create trigger HumanResources.trg_Department
on HumanResources.Department
after insert
as
print N'触发器被激活'
go
disable trigger HumanResources.trg_Department
on HumanResources.Department
--因为触发器被禁止了,所以下面的Insert执行后不会返回打印消息
insert HumanResources.Department(name,GroupName) values('Construction','Building Services')
go
--enable trigger命令启用触发器
enable trigger HumanResources.trg_Department
on HumanResources.Department
--再次插入
insert HumanResources.Department
(Name,GroupName)
values('Cleaning1','Building Services')
--限制触发器嵌套
/*
当触发器触发之后执行的动作会触发另一个触发器,那个触发器然后又触
发另外一个触发器的时候就发生了触发器嵌套
SQL Server 2005最大嵌套级别是32层
*/
--禁止和启用触发器嵌套
use master
go
--禁止嵌套
exec sp_configure 'nested triggers',0
reconfigure with override --由于服务器选项包含当前的配置和运行的配置,此命令用于更新运行时值以使之立即生效
go
--启用嵌套
exec sp_configure 'nested trigger',1
reconfigure with override
go
--控制触发器递归
/*
如果触发器触发后执行的行为会导致相同的表触发器再次触发,那么这种触发器嵌套就被认为是递归的。当触发器的触发影响
其他表的时候,如果触发器还会影响原始表,引起原来的触发器再次触发,也会发生递归
*/
--启用和禁止递归触发器
alter database AdventureWorks --是否允许数据库内递归触发器
set recursive_Triggers on
--查看数据库设置
select is_recursive_triggers_on
from sys.databases
where name='AdventureWorks'
--防止递归
alter database AdventureWorks
set recursive_triggers off
--查看数据库设置
select is_recursive_triggers_on
from sys.databases
where name='AdventureWorks'
--设置触发器触发次序
--创建一个测试表并为之增加3个DML的Insert触发器,然后使用sp_settrigger来定义触发器次序
create table dbo.TestTriggerOrder
(
TestID int not null
)
go
create trigger dbo.trg_i_TestTriggerOrder
on dbo.TestTriggerOrder
after insert
as
print N'我将被第一个触发'
go
create trigger dbo.trg_i_TestTriggerOrder2
on dbo.TestTriggerOrder
after insert
as
print N'我将最后被触发'
go
create trigger dbo.trg_i_TestTriggerOrder3
on dbo.TestTriggerOrder
after insert
as
print N'我将不是第一个也不是最后一个被触发'
go
exec sp_settriggerorder 'trg_i_TestTriggerOrder','First','INSERT'
exec sp_settriggerorder 'trg_i_TestTriggerOrder2','Last','INSERT'
insert dbo.TestTriggerOrder values(2);
go
--删除触发器
--删除DML触发器
drop trigger dbo.trg_i_TestTriggerOrder
--删除多个触发器
Drop trigger dbo.trg_i_TestTriggerOrder2,dbo.trg_i_TestTriggerOrder3
--删除DDL触发器
Drop trigger db_trg_RestrictIndexChanges
create database Book
create table booker(
bookno int primary key not null,
bookname varchar(50) not null,
bookprice float not null,
bookcount int not null,
bookwriter varchar(50) not null
)
insert into booker values(1,'王晓京',2000,25,'李春春')
insert into booker values(2,'王晓京2',2000,25,'李春春2')
insert into booker values(3,'王晓京3',2000,25,'李春春3')
select *from booker
-------全局变量------------------------
select @@version --查看sql的版本号
select @@error --返回最后执行的 Transact-SQL 语句的错误代码。
-------变量的声明--------------------------------------------------
declare @变量名 int--声明
set @变量名=10 --赋值
select @变量名 --输出变量值 以上三步同时执行有效
if(1=1)
begin
select *from booker
end
------------------------------------------------游标-------
--------------------------.1声明游标 语法: declare 游标名 cursor for select_statement
declare cursor_name cursor
for select bookno,bookname from booker where bookcount=25
--------------------------.2打开游标 语法: open 游标名
open cursor_name
--------------------------.3提取游标值 语法:fetch next from 游标名 while(@@fetch_status=0) begin fetch next from 游标名 end
fetch next from cursor_name while(@@fetch_status=0)--返回被 FETCH 语句执行的最后游标的状态,而不是任何当前被连接打开的游标的状态。
-- 返回值 描述
-- 0 FETCH语句成功。
-- -1 FETCH语句失败或此行不在结果集中。
-- -2 被提取的行不存在。
begin
fetch next from cursor_name
end
--------------------------.4关闭游标 close 游标名
close cursor_name
--------------------------.5删除游标 deallocate 游标名
deallocate cursor_name
create database company--建立数据库
go
create table stu_info--建表
(
stu_id int primary key,
stu_name varchar(30) not null,
stu_sex char(2) ,
salary money ,
birthday smalldatetime
)
go
--插入数据
insert into stu_info values(1,'张三','男',1000,'2000-10-10')
insert into stu_info values(2,'李四','女',2000,'2001-10-10')
insert into stu_info values(3,'王五','男',3000,'2002-10-10')
insert into stu_info values(4,'张六','男',4000,'2003-10-10')
go
select * from stu_info
---------------------------------------------------
--创建存储过程
------------------------------------------------
--11111创建(一个无参无返的)存储过程
create proc wfwc
as
select * from stu_info
--执行 存储过程 exec 存储名
exec wfwc
drop proc wfwc--删除存储过程 drop proc 存储名
--22222创建(有输入参数的)存储过程
create proc wfyc
@salary int = 1000, --整形的 无默认值的 输入参数
@sex varchar(2) = '女'--字符类型的 无默认值的 输入参数
as
select * from stu_info where salary > @salary and stu_sex = @sex
exec wfyc --执行的是默认参数值的(此时是有默认参数的,若没有默认参数的,在执行的过程中必须传参 且数据类型一致)
exec wfyc 2000,'男' --执行传过去的参数 此时传过去的参数又先后顺序的
exec wfyc @salary=2000,@sex='男'
--或者
exec wfyc @sex='男',@salary=2000
--修改(上面的)存储过程 由 有默认值的 修改为 无默认值的
alter procedure wfyc
@salary int,
@sex varchar(10)
as
select * from stu_info where salary>@salary and stu_sex=@sex
exec wfyc 1000,'男' --此时必须有参数
drop procedure wfyc
--33333新建一个(有输入、输出参数的) 存储过程
create procedure wfyc_output
@salary int,
@sex varchar(10),
@count int output--多了一个输出参数 与输入参数不同的是 后面 有 output
as
set @count=
(select count(*) from stu_info where salary>@salary and stu_sex=@sex)
--sql执行语句
declare @num int--声明局部变量
execute wfyc_output 1000,'男',@num output--执行有输出参数的存储过程时,输出参数比较特殊 注意区别: 事先声明的一个同类型的变量 output
select @num as N'性别是"男",工资超过"1000"的员工数' --打印出 变量的值
--以上三句须同时执行
drop procedure wfyc_output---删除存储过程
--44444存储过程(有输入输出参数的 有返回值的)
create procedure yfyc__output
@salary int,
@sex varchar(10),
@count int output
as
set @count= --set 赋值
(select count(*) from stu_info where salary>@salary and stu_sex=@sex)
if @count<>0
begin
return 1
end
else
begin
return 0
end
--sql执行
declare @count int,@result int--声明变量( 只要有声明的变量 和此变量有关系的执行存储过程 都要同时执行)
exec @result=yfyc__output 1000,'男',@count output--执行存储过程
print @count --打印出 符合要求的查询的 数目
print @result --打印出 执行存储过程时的返回值
drop proc yfyc__output
--创建存储过程(分页)
create proc select_stu_info10
--页码 2,每页记录数 2
@pageNumer int=2,--不管总共有多少条记录,前面按记录数分页,最后剩下不够记录数的也算一页
@pageSize int=2
as select top (@pageSize) *from stu_info --top 2 指每页记录数 即@pageSize ()不能少
where stu_id not in(select top ((@pageNumer-1)*@pageSize)stu_id from stu_info order by stu_id asc)
exec select_stu_info10 --显示最后一页的记录数据
select *from stu_info
/*注意:SQL中不区分大小写的
新增的:
--备份数据库
backup database database_name to disk='url\name.bak'--database_name 一定不能加单引号的‘’,另外为备份的数据库区别名.bak
--回复还原数据库
restore databse database_name from disk='url\name.bak'--还原的数据库名子可以自定义的
--重命名数据库
sp_renamedb 'database_oldName','database_newName' --更改数据库名称这里的单引号必须有的
--重命名表
sp_rename 'table_oldName','table_newName' --忘记两个表明之间的逗号
--重命名列
sp_rename 'table.字段名','new 字段名','column '
--查看表的信息
sp_help table_name --1
sp_columns table_name --2
sp_pkeys table_name --查看主键信息
多列的主键约束
alter table table_name add constraint name primary key(字段1,字段2)
删除主键
alter table table_name drop constraint name
case
when then
when then
else
end
数据转换
1.cast cast(@a as varchar(10))
2.conver (varchar(10),@a)
len('aaaa')--求字符的长度
*/
--建库
create database database_name
--1建表(外键在允许为空的情况下是可以null的)
create table table_name
(
stu_no int identity (1,1) ,
stu_name char(10) not null,
stu_age int check(stu_age <60 and stu_age >20) not null,
stu_sex char(2) check(stu_sex = '男' or stu_sex ='女') default'男'
)--显示 select *from stu_info
--2【插入数据】
--.1向所有的列插入数据:
(identity 标识列自增的,不用插入数据,也不用null占位,否则会报错 在有标识列的表中插入数据时,即使插入数据错误,但是标识列也在自增;
比较:在mysql中 自增列是 auto_increment 且必须是主键 primary key
default 必须有数据 在允许为空时是null 也行,插入null 则值就是null 不会是默认值 ' ' 同理
--.2向指定的列插入数据
identity 标识列也是不能插入 总之标识列不能插入数据的 ;
default 默认值 不向其插入值时是默认值
--3【改数据库名】
--语法:alter database 原数据库名 modify name= 新库名
alter database 笔记 modify name = 同学信息表 但分离是还是原数据库名
--4【改表增/删列】
--a.增加新列 语法:alter table 表名 add 列名 列名的类型 约束
alter table stu_info add stu_adress varchar(10) not null default '郑州' --非空时一定要有一个默认值
alter table stu_info add stu_tel int
--b.删除列 语法:alter table 表名 drop column 列名 [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
alter table stu_info drop column stu_no --没有约束能够直接删除列(这里的约束不包括 null , not null)
alter table stu_info drop column stu_adress--有约束不能直接删除,则必须先删除约束 再删除列
alter table stu_info drop DF__stu_info__stu_ad__79A81403 -- DF__stu_info__stu_ad__79A81403 删除列时的出现的约束的地址
-c.修改
alter table table_name alter column_name 约束 《一般是null 在有数据时不能为not null》
alter table stu_info alter column stu_name char(10) not null
--【删除一条数据】
--语法:delete from 表名 where 条件1--这里不加where条件 会删除全部数据
--删除‘张军’中的数据
delete from stu_info where stu_name='张军'--张军的所有信息都删掉了
--------------------------------------------------------------------------------------------显示 select *from stu_info
--删除具有 统一特性 的数据
--删除性别是男的数据
delete from stu_info where stu_sex='男'--男士的所有信息全都删除
delete from stu_info where stu_no IN (3,4)--通过使用IN关键字
--【查询数据】
--语法1:select *from 表名 《查询的是 (这个表中) 所有列的数据》
--语法2:select 列名1 from 表名1 where 条件1 《查询的是表名1中符合条件1的列名1的数据》
--语法3:select *from 表名1 where 条件1 《查询的是表名1中符合条件1的 所有列 的数据》
select stu_name from stu_info --没有where条件查询的是表中所有的 stu_name 数据
select * from stu_info where stu_adress='金水路11号'
select stu_no AS 学号 ,stu_name 姓名,stu_age 年龄 from stu_info where stu_age <60 and stu_age > 50--通过AS ,空格 ,= ,为列取别名
select distinct stu_name AS 姓名 from stu_info where stu_age <60 and stu_age > 40 --通过使用关键字distinct 把不同的屏蔽掉
select stu_no AS 学号,stu_name 姓名,stu_age 年龄 from stu_info where stu_no IN (4,8)--通过使用IN关键字查询 有其一就成立
--查询结果排序 order by desc
select stu_name AS 姓名,stu_age 年龄 from stu_info order by stu_age desc--使用 order by stu_age desc按年龄从大到小排列
select top 3 stu_name as 姓名 from stu_info order by stu_age desc --使用top关键字 top n 或 百分比 查询前 n行 数据
------------------------------------另一个数据库的表中
--查询结果分组group by
create database chshi
alter database chshi modify name= 超市
create table huo
(
title char(20) not null,
type char(20) not null,
price float not null,
priduct_id int not null
)
insert into huo values ('洗衣粉','日用品',4.8,2000)
insert into huo values ('牙刷','日用品',2.0,2500)
insert into huo values ('apple糖','食品',5.0,1000)
---------------------------------------select *from huo
select title as 名称, sum(priduct_id)as 数量 from huo group by title <order by title> --查寻每种商品的数量
--sum函数 --可以不写
--avg函数
--select type as 类型,avg(priduct_id*price)as 平均价 from huo group by type order by type
select title as 名称,type 类型 ,avg(priduct_id*price)as 平均价 from huo group by title,type order by title,type
--使用count函数查询每种类型中有几种产品
select type as 类型,count(title) as 种类数 from huo group by type order by type
select type as 类型,title 名称 , max(price)as 最高价格 from huo group by type ,title order by type ,title/**/
select type as 类型,title 名称, sum(priduct_id*price)as 订单价格 from huo group by type ,title having sum(priduct_id*price)>7000
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/***************************************************************************************************************************************************************************/***/
-- 创建数据库
create database stu_info --创建 创造 ddl create database 数据库名
go
--drop database stu_info--删除数据库 ddl create drop alter
create database student2
use stu_info --以后每一步操作 都存到这个数据库中
create table student1--创建表 在stu_info中 表名
(
--表中应该有相应的字段 列名
stu_num int constraint stu_num_union unique,
stu_name varchar(8) not null,
stu_age int check(stu_age<100 and stu_age>0),--and 相当于逻辑与 与符
stu_sex char(4)
)
create database 胡书然
/* unique 唯一约束
语法:constraint 字段名后面_union unique
强迫给某一字段和unique约束建立关系
unique和primary key 不允许有相同值 重复值
unique允许有一个是空值
default约束:防止空值 给他一个默认值
default ‘男’ 有效防止空值 防止无效值出现
在企业管理其中怎样设置默认值:打开表界面 =》 找到操作表右键
=> 设计表 =》 下方默认值中,设置相应默认值
*/
--修改表 alter DDL database define language
---------------------------ddl 对象是表,库---------------------------------------
--create 创建 drop删除 alter修改
/*修改表的操作
alter语法有几种
1.add方式 增加列
语法:alter table 表名 add 列定义、完整性定义
例:在stu_info中添加两个字段 班级号列 地址列 列名 */
alter table student1 add cla_id int
alter table student1 add address varchar(10)
/* 2、alter方式 修改列的属性
语法: alter teble 表名 alter column 列名 类型
例:把address列宽增加到20
alter table student1
alter column address varchar(20)
注意问题:1、不能修改列名 字段名称
2、不能将已定义可以有空值的列定义修改成 not null
3、若已有数据不能减少数据列,也不能修改数据类型
4、只能修改null或者not null约束,其他类型约束放在修改前
必须删除,然后重新创建修改过的列的约束。*/
-- 3.drop 删除表 约束
alter table 表名 drop column 列名 ----删除列
drop database 数据库名 ----删除数据库
drop table 表名 ----删除表
drop constraint 约束名 ----删除约束
-----------------dml-----对象是数据---------------
1.insert into 表名 values 数值 -----插入数据
2. select *from 表名1 ----查询表1中所有列的数据
select 列名1 from 表名1 ----查询表1中列名1的数据
3. update 表名 set 列名=更新的值 where 条件 ----更新数据
4.delete from 表名 where 条件 ----删除的是一条记录数据
1.语法:insert into 表名 [列名1,列名2.... ] values 【值1,值2....】
列名数量须和值的数相对应,如果不写列名,直接插入值时,空值应该‘
空出(在所在的列允许为空的前提下)
例:在student1表中插入一学生数据
学号 007
姓名 007
性别 男
年龄 20
班级好 1
insert into student1 values(007,'007',20,'男',1,'')
注意:1.1、必须使用逗号将各个数据分开,字符型,时间类型 用单引号 '' 分隔
1.2、每条记录必须在每个属性上都有values值,且值在自居中的 ,排列应和表中值的顺序一致。
1.3、对于into子句,没有出现的列,保留空值位置
1.4、在表定义时,有not null约束的属性列,将不能去空值
--2.select 查询 查询语言 select where
--select用于查询数据,也可以用来调用函数或者局部变量
语法:select 选择列表(* 代表表中所有的列) from 表名 where 检索条件
注意:2.1、选择列表中,可以包含几个列名或者表达式,用逗号隔开
用来指示返回那些数据,
from子句,包含提供数据表的名称 从那里查询
2.2、当选择列表中含有列名时,每一个select子句必须有一个from子句
where用于写出检索条件。
--查询全体学生所有信息
select * from student1
select stu_age
from student1
where stu_name='胡书然'
--3.update修改,更新
语法:update 表名 set 列名=更新的值 where 条件
例:update用于修改表中已经存在的数据
可以一次修改多行,也可以修改一行
例:修改一行:把007 的 姓名换成 胡书然
update student1
set stu_name='胡书然'
where stu_age=20
例:将所有学生年龄全部加1
update student1
set stu_age=stu_age+1
where stu_age<22
insert into student1 values(321,'0012',20,'男',1,'')
--5.delete 删除
where 要删除记录的条件
可以删除一行 也可以删除所有数据
没有where就是删除所有数据
delete from student1
go
drop table student1
select * from student1
delete from student1
where stu_name='胡书然'
今天:语言 ddl create drop alter
dml update delete insert select
dcl grant revoke
时间函数:
select getdate()
select year('2000-10-10')
select year(getdate())
select datediff(hour,'1988-10-01',getdate())
正则表达式限制文本框只能输入数字
许多时候我们在制作表单时需要限制文本框输入内容的类型,下面我们用正则表达式限制文本框只能输入数字、小数点、英文字母、汉字等各类代码。
1.文本框只能输入数字代码(小数点也不能输入)
<input on
2.只能输入数字,能输小数点.
<input on
<input name=txt1 on
3.数字和小数点方法二
<input type=text t_value="" o_value="" on
可以封装成单独的函数
function keyPress(ob) {
if (!ob.value.match(/^[\+\-]?\d*?\.?\d*?$/)) ob.value = ob.t_value; else ob.t_value = ob.value; if (ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) ob.o_value = ob.value;
}
function keyUp(ob) {
if (!ob.value.match(/^[\+\-]?\d*?\.?\d*?$/)) ob.value = ob.t_value; else ob.t_value = ob.value; if (ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) ob.o_value = ob.value;
}
function onBlur(ob) {
if(!ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/))ob.value=ob.o_value;else{if(ob.value.match(/^\.\d+$/))ob.value=0+ob.value;if(ob.value.match(/^\.$/))ob.value=0;ob.o_value=ob.value};
}
只需在调用,传入this对象即可!
4.只能输入字母和汉字
<input on
5.只能输入英文字母和数字,不能输入中文
<input on
6.只能输入数字和英文
<input on
7.小数点后只能有最多两位(数字,中文都可输入),不能输入字母和运算符号:
<input on
8.小数点后只能有最多两位(数字,字母,中文都可输入),可以输入运算符号:
<input on