[SQL] MSSQL update 语句中的关联

将tableA 表中的所有title 用tableB中的titlename 更新掉,如果tableB中存在对应的关系

update tableA as a

set a.title = (select b.titlename from tableB as b where a.id =b.xid)

 

上面的写法,无法在MSSQL中进行执行,因此

我们可以使用函数变相 脚本 

 

传入参数相同

 

update tableA

set title =fn_getXTitle(id)

 

fn_getXTitle

ALTER FUNCTION [dbo].[fn_getXTitle]
(
  @id nVARCHAR(50)
) 
RETURNS  nVARCHAR (50)

AS
BEGIN
declare @title nvarchar(50)
    set @title =select b.titlename from tableB as b where b.xid =@id

RETURN @title

end

传入参数不同

 

 --创建功能函数

create FUNCTION [dbo].[fn_getdatafromoldve]
(
  @OLDVE nVARCHAR(50)  
  ,@Type nVARCHAR(50) 
) 
RETURNS  nVARCHAR (50)
AS
BEGIN
declare @BO_ID nvarchar(50)
declare @NEWVE nvarchar(50)
declare @PjtNO_X nvarchar(50)


IF @TYPE ='M'  
  BEGIN
  set @NEWVE =(select top 1 NEWVE from [XXXX].[dbo].[MIG_MAPPING1] where OLDVE =@OLDVE and FIELDNAME='PSPIX')
  if @NEWVE is not null
  begin
   set @BO_ID =(select top 1 BO_ID from [XXXX].[dbo].[MIG_ORDER_BASE] WHERE ORDER_ID =@NEWVE)
   if @BO_ID is not null 
   begin
    RETURN @BO_ID
   end 
   else
   begin
    RETURN @OLDVE
   end
   
   
  end
  else
   begin
    RETURN @OLDVE
   end
  END
IF @TYPE ='P' 
  BEGIN
  set @NEWVE =(select top 1 NEWVE from [XXXX].[dbo].[MIG_MAPPING1] where OLDVE =@OLDVE and FIELDNAME ='PSPID')
  if @NEWVE is not null 
   begin
    RETURN @NEWVE
   end 
   else
   begin
    RETURN @OLDVE
   end
  
   
  END
IF @TYPE ='PX' 
  BEGIN
  set @PjtNO_X =(select top 1 NEWVE from [XXXX].[dbo].[MIG_MAPPING1] where OLDVE =@OLDVE and FIELDNAME ='PSPIX')
  
    if @PjtNO_X is not null 
   begin
    RETURN @PjtNO_X
   end 
   else
   begin
    RETURN @OLDVE
   end
    
  END  


RETURN @OLDVE
END
--执行的脚本
UPDATE [XXXX].[dbo].[tb_PrjMethod] set [PjtNo]=[dbo].[fn_getdatafromoldve](PjtNo,'P')    

 

posted @ 2016-06-15 11:05  Areas  阅读(450)  评论(0编辑  收藏  举报