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

最近做了三个问题,虽然很小,而且实现的也略显笨拙,但还是想记录下来,供大家参考一下,也满足一下自己的一种虚荣心,呵呵:)
问题一:
要求对一表中的字符数据进行自动编码,基本要求大概是:第一条数据编码为'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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值