34,590
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb')is not null drop table tb
go
create table tb([Name] varchar(10) check ( PATINDEX('%[^a-z0-9]%',[name])= 0))
insert tb select 'ad12'
insert tb select 'a'
insert tb select '12'
insert tb select '--'
/*伺服器: 訊息 547,層級 16,狀態 1,行 1
INSERT 陳述式與 COLUMN CHECK 條件約束 'CK__tb__Name__0E6EF216' 發生衝突。衝突發生於資料庫 'db_Study',資料表 'tb', column 'Name'。
陳述式已經結束。
*/
--錯了
if object_id('tb')is not null drop table tb
go
create table tb([Name] varchar(10) check ( PATINDEX('%[^a-z]%',[name])= 0))
------------------------------------1
create table tb([Name] varchar(10) check ( PATINDEX('%[^a-z]%',[name])= 0))
go
insert into tb select 'asdf'
insert into tb select 'asdf;'
insert into tb select 'asdf1'
select * from tb
/*服务器: 消息 547,级别 16,状态 1,行 1
INSERT 语句与 COLUMN CHECK 约束 'CK__tb__Name__20CCFFE6' 冲突。该冲突发生于数据库 'csdn_test',表 'tb', column 'Name'。
语句已终止。
服务器: 消息 547,级别 16,状态 1,行 1
INSERT 语句与 COLUMN CHECK 约束 'CK__tb__Name__20CCFFE6' 冲突。该冲突发生于数据库 'csdn_test',表 'tb', column 'Name'。
语句已终止。
Name
----------
asdf
(所影响的行数为 1 行)
*/
drop table tb
---------------------------------2
create table tb([Name] varchar(10) )
go
go
create trigger tr_insert
on tb
instead of insert
as
begin
if exists(select 1 from inserted where PATINDEX('%[^a-z]%',[name])>0)
begin
raiserror('INSERT 语句添加除了a-z的其它字符', 16, 1)
ROLLBACK
end
else
insert into tb select * from inserted
end
go
insert into tb select 'asdf1'
服务器: 消息 50000,级别 16,状态 1,过程 tr_insert,行 9
INSERT 语句添加除了a-z的其它字符
insert into tb select 'asdf;'
服务器: 消息 50000,级别 16,状态 1,过程 tr_insert,行 9
INSERT 语句添加除了a-z的其它字符
insert into tb select 'asdf'
select * from tb
Name
----------
asdf
asdf
(所影响的行数为 2 行)
drop table tb
declare @a varchar(50)
set @a ='afasdf1fdf'
if PATINDEX('%[^a-z]%',@a) > 0
print 'error'
结果:
error
if PATINDEX('%[^a-z]%',col) > 0
print 'error'
create table tb([Name] varchar(10) check ( [name] like '%[a-z]%') )