搜课云网 > 上海内威培训 > 资讯总汇 > 一道面试题带来的思考

一道面试题带来的思考

机构:上海内威培训 时间:2016-01-28 08:42:52 点击:546

  例:有一合同表Contract

  Id Name Total buget

  1 合同名称 100 102,22

  2 合同名称2 300 ,102,22,

  3 合同名称3 200 ,103,23,

  要求:用SQL语句更新表的buget字段,如果前后没有","要加上","(即一个英文逗

  号)。(10分)

  创建表数据:

  [ruby] view plaincopyprint?

  use Testdb2

  go

  IF NOT OBJECT_ID('[Contract]') IS NULL

  DROP TABLE [Contract]

  GO

  Create table [Contract]

  (ID int primary key identity(1,1)

  ,[Name] nvarchar(50) null

  ,Total float null

  ,buget Nvarchar(500) null

  )

  go

  insert into [Contract]

  select '合同名称', 100,'102,22'

  union all

  select '合同名称2', 300,',102,22,'

  union all

  select '合同名称3', 300,'101,23,'

  分析:这道题乍看很简单,由于肯定用到Replace,所以很自然的结合

  left,right,从而得到以下语句

  方法一 :

  [ruby] view plaincopyprint?

  update [Contract] set buget=','+buget where left(buget,1)=','

  update [Contract] set buget=buget+',' where right(buget,1)=','

  如果能写成一个 SQL语句,可以加1分。

  [ruby] view plaincopyprint?

  update [Contract]

  set buget=(case when (left(buget,1)!=',' and right(buget,1)!=',') then

  ','+buget+','

  when left(buget,1)!=',' then ','+buget

  when right(buget,1)!=',' then buget+','

  else buget

  end)

  如果能从字符串的开关和结尾这个思路出发,结合Reverse,可以提到如下方法:

  方法二:

  [ruby] view plaincopyprint?

  update [Contract] set buget=','+buget where charindex(',',buget)<>1

  update [Contract] set buget=buget+',' where charindex(',',reverse

  (buget))<>1

  该方法,主要涉及charindex函数和reverse函数。

  说实话,我当时就这两种思路,这也是SQL中常见的基本用法。但出人意料的第三

  种方法出现了

  了解更多关于软件方面的知识,请访问上海软件培训学校

师资介绍