选择更新

时间:2013-02-01 15:48:14

标签: sql sql-server-2008-r2 sql-update

我有以下表格:

TARIF_COURANT

CODE_TARIF   NO_CLIENT   ZONE  UNITE
  A_0_300       8585      1      8
  A_0_300       8585      1      5

T_TARIF_ZONE

NO_ID   LIBELLE
  1       A
  2       B

T_UNITE

NO_ID   LIBELLE
  8       MOT
  5       FUT

我如何Update我的表格TARIF_COURANT才能获得此结果:

 CODE_TARIF     NO_CLIENT   ZONE   UNITE
 A-MOT_0_300       8585      1       8
 A-FUT_0_300       8585      1       5

我试过这样:

UPDATE
    TARIF_COURANT
SET
    TARIF_COURANT.CODE_TARIF =  T_TARIF_ZONE.LIBELLE +'-'
       + RTRIM(LTRIM( T_UNITE.LIBELLE) )+'_'
       +CONVERT(varchar, [TR_DEB]) 
       +'_'+CONVERT(varchar, [TR_FIN])
FROM
    TARIF_COURANT
     left join T_UNITE on TARIF_COURANT.unite = T_UNITE.NO_ID
     left join T_TARIF_ZONE on TARIF_COURANT.zone = T_TARIF_ZONE.NO_ID
      where no_client = '850673' and unite != 1
ON
    TARIF_COURANT.CODE_TARIF = TARIF_COURANT.CODE_TARIF

1 个答案:

答案 0 :(得分:3)

UPDATE t
SET t.CODE_TARIF = ttz.LIBELLE 
  + '-' + RTRIM(LTRIM( tu.LIBELLE) )
  + '_' + CONVERT(VARCHAR(32), [TR_DEB]) -- what table does this come from? 
  + '_' + CONVERT(VARCHAR(32), [TR_FIN]) -- what table does this come from?
--------------------------^^ don't be lazy! Specify a length!
FROM
  dbo.TARIF_COURANT AS t -- use aliases and proper schema prefixes
LEFT OUTER JOIN
  dbo.t_UNITE AS tu
  ON t.unite = tu.NO_ID
LEFT OUTER JOIN
  dbo.T_TARIF_ZONE AS ttz
  ON t.zone = ttz.NO_ID
WHERE
  no_client = '850673' -- what table does this come from?
  and unite <> 1;      -- what table does this come from?