自定義slipt函數:app
/****** Object: UserDefinedFunction [dbo].[f_split] Script Date: 05/11/2012 10:01:16 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[f_split]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[f_split]
GO函數
USE [mytest]
GOfetch
/****** Object: UserDefinedFunction [dbo].[f_split] Script Date: 05/11/2012 10:01:16 ******/
SET ANSI_NULLS ON
GO.net
SET QUOTED_IDENTIFIER ON
GOip
create function [dbo].[f_split](@aString varchar(8000),@pattern varchar(10))
returns @temp table(a varchar(100))
--實現split功能 的函數
--說明:@aString,字符串,如a:b:c;@pattern,分隔標誌,如 :
as
begin
declare @i int
set @aString=rtrim(ltrim(@aString))
set @i=charindex(@pattern,@aString)
while @i>=1
begin
insert @temp values(left(@aString,@i-1))
set @aString=substring(@aString,@i+1,len(@aString)-@i)
set @i=charindex(@pattern,@aString)
end
if @aString<>''
insert @temp values(@aString)
return 字符串
end
GO
-----------------------------------------------------------------------------------------------------get
建立處理的triggerstring
--建立insert插入類型觸發器
if (object_id('tgr_table_insert', 'tr') is not null)
drop trigger tgr_table_insert
go
create trigger tgr_table_insert
on [bpo].[tableA] AFTER INSERT --插入觸發
as
begin
--定義變量
declare @id varchar(50), @name varchar(4000),@sliptname varchar(50)
--在inserted表中查詢已經插入記錄信息
select @id = id, @name = name from inserted
if(@id is not null and @name is not null)
begin
declare mycursor cursor for select * from dbo.f_split(@name ,';') -- 以;截取字段,保存在遊標裏
open mycursor -- 打開遊標
fetch next from mycursor into @sliptname
while(@@fetch_status=0) -- 判斷遊標狀態,0爲fetch語句成功,1爲fetch語句失敗,2爲被提取的行不存在
begin
insert into [bpo].[tableB] values(@id, @sliptname) -- 向tableB表插入取的記錄信息
fetch next from mycursor into @sliptname -- 遊標取的下一條記錄
end;
close mycursor; -- 關閉遊標
DEALLOCATE mycursor;it
end;
--print '添加tableB信息成功!';
end
GOio