我有一张存储处方药物信息的表格,需要每天从中央处方集更新.临时表与药物表相同.临时表数据可以与主表相同(并且在大多数情况下也是如此),或者它可以具有更新的行或新行.
我有一个存储过程来更新主表,但它失败,因为它不会更新NULL行(如果临时表中有一个新行).
这是一个MSSQL Server 2005.
我在哪里错了:
-- Insert statements for procedure here UPDATE [RX_Billing].[dbo].[FS_Drug] SET [TRADENAME] = [RX_Billing].[dbo].[FS_Drug_TEMP].[TRADENAME] ,[CDM] = [RX_Billing].[dbo].[FS_Drug_TEMP].[CDM] ,[NDC] = [RX_Billing].[dbo].[FS_Drug_TEMP].[NDC] ,[IP_COST] = [RX_Billing].[dbo].[FS_Drug_TEMP].[IP_COST] ,[OP_COST] = [RX_Billing].[dbo].[FS_Drug_TEMP].[OP_COST] ,[HH_COST] = [RX_Billing].[dbo].[FS_Drug_TEMP].[HH_COST] ,[VAR_COST] = [RX_Billing].[dbo].[FS_Drug_TEMP].[VAR_COST] ,[LSTUPDATE] = [RX_Billing].[dbo].[FS_Drug_TEMP].[LSTUPDATE] FROM [RX_Billing].[dbo].[FS_Drug] RIGHT OUTER JOIN [RX_Billing].[dbo].[FS_Drug_TEMP] ON [RX_Billing].[dbo].[FS_Drug].[TRADENAME] = [RX_Billing].[dbo].[FS_Drug_TEMP].[TRADENAME]
编辑:
我选择了Rory的代码.谢谢,这很好用.
Orion Edwards的注释:UPSERT/MERGE正是我想要的,但SQL Server 2005不支持它.显然它是有计划的,但没有发布.它在Server 2008中可用.(从Interwebs告诉我的内容.)
标准方法是执行UPDATE然后执行INSERT:
-- UPDATE rows using an INNER JOIN with matching TRADENAME. No need to update TRADENAME column. UPDATE drug SET [CDM] = tmp.[CDM] , [NDC] = tmp.[NDC] , [IP_COST] = tmp.[IP_COST] , [OP_COST] = tmp.[OP_COST] , [HH_COST] = tmp.[HH_COST] , [VAR_COST] = tmp.[VAR_COST] , [LSTUPDATE] = tmp.[LSTUPDATE] FROM [RX_Billing].[dbo].[FS_Drug] drug INNER JOIN [RX_Billing].[dbo].[FS_Drug_TEMP] tmp ON drug.[TRADENAME] = tmp.[TRADENAME] -- Insert rows that don't have matching TRADENAME INSERT INTO drug SELECT tmp.[TRADENAME] , tmp.[CDM] , tmp.[NDC] , tmp.[IP_COST] , tmp.[OP_COST] , tmp.[HH_COST] , tmp.[VAR_COST] , tmp.[LSTUPDATE] FROM [RX_Billing].[dbo].[FS_Drug] drug RIGHT OUTER JOIN [RX_Billing].[dbo].[FS_Drug_TEMP] tmp ON drug.[TRADENAME] = tmp.[TRADENAME] WHERE drug.[TRADENAME] IS NULL
您可能还想删除或标记为已删除药物中不再存在于tmp中的任何记录.将此作为与UPDATE相同的单独语句,但使用LEFT OUTER JOIN,其中tmp.TRADENAME为NULL.