MS-SQLServer2000中字符型数据自动编码的实现

王朝mssql·作者佚名  2006-01-09
宽屏版  字体: |||超大  

最近做了三个问题,虽然很小,而且实现的也略显笨拙,但还是想记录下来,供大家参考一下,也满足一下自己的一种虚荣心,呵呵:)

问题一:

要求对一表中的字符数据进行自动编码,基本要求大概是:第一条数据编码为'FM00000',第二条为'FM00001',第三条为"FM00002',以次类推;刚好最近在练习写触发器,简单实现了一下.

实现思路:

建立主键为identity的表,利用表主键的identity属性,在触发器中拼成所需字符串,当向表insert数据时更新相应字段值

--建表

CREATE TABLE [dbo].[test_table] (

[ID] [int] IDENTITY (1, 1) NOT NULL ,

[NAME] [varchar] (80)

) ON [PRIMARY]

GO

--建立触发器

CREATE trigger test_trigger on test_table

for insert

as update test_table

set name =substring('FM'+stuff('00000',5-len(i.id)+1,len(i.id),CAST(i.id AS char(5))),1,7)

from inserted i where i.id=test_table.id

GO

--测试插入语句

insert into test_table select 1 union select 2 union select 3 union select 4 union select 5

如不使用identity的字段上面的触发器也可以做修改,如下:

alter trigger test_trigger on test_table

for insert

as

declare @next_seq int

select @next_seq=(select cast ((select substring(max(name),3,5) from test_table) as int)+1)

update test_table

set name =substring(stuff('FM00000',7-len(@next_seq)+1,len(@next_seq),cast(@next_seq as char(5))),1,7)

--或者如此,这样更简单:

-- set name ='FM'+right('00000'+cast(@next_seq as varchar),5)

from inserted i where i.id=test_table.id

GO

问题二:

查询中实现对价格等货币值格式化为$0,000.00样式的问题,实现如下:

货币转换:

select '$'+convert(varchar,cast(tb字段 as money),1)

示例: select '$'+convert(varchar,cast(111111.5 as money),1)

问题三:

编写触发器,对一表中插入的日期数据修改为该日期所处月份的最后一天

脚本如下:

--建测试表

create table test_table (

id int IDENTITY(1,1) primary key,

mytime datetime NOT NULL)

GO

--建触发器

create trigger date_change_trigger on test_table

for insert

as

update test_table

set mytime = (select dateadd(ms,-3,dateadd(m,datediff(m,0,(select mytime from inserted))+1,0)))

from inserted i where test_table.id=i.id

GO

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有