如何为此构建动态SQl?

时间:2022-09-22 16:31:48

I have to create a Procedure with dynamic SQL and generate the Update Statements.

我必须使用动态SQL创建一个过程并生成更新语句。

I have tables

我有桌子

Col.TMap.T_Mp

 ID   M_Type  ID_F     SF1      SF2
  1   Acc     ACC_ID   AC_ID    NULL
  1   STA     STA_ID   ST_ID    NULL
  1   CHa     Cha_ID   CH_ID    NULL

ACC

ID    AC_ID   SV1   SV2     SO1    SO2
1     12      6     NULL    =      NULL

STA

ID     STA_ID      SV1     SV2      SO1    SO2
1      1           Open    NULL     =      NULL
1      2           CLosed  NULL     =      NULL

CHa

ID    CHa_ID    SV1    SV2    SO1    SO2
1     1         PH     NULL   =      NULL
1     2         EM     NULL   =      NULL

I need to update Ms.AT.AT_CRAW_Dmtemp table with ACC_ID,STA_ID and CHA_ID from the above tables:

我需要使用上面的表中的ACC_ID,STA_ID和CHA_ID更新Ms.AT.AT_CRAW_Dmtemp表:

The out put should be:

输出应该是:

UPDATE  mt 
SET ACC_ID = ac.ACC_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN Acc ac ON t.AC_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt 
ON mt.[SRID] = t.[RID]



UPDATE  mt 
SET STA_ID = ac.STA_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN STA ac ON t.ST_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt 
ON mt.[SRID] = t.[RID]



UPDATE  mt 
SET CHa_ID = ac.CHa_ID
FROM Ms.AT.AT_CRAW t
INNER JOIN CHa ac ON t.CH_ID=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt  
ON mt.[SRID] = t.[RID]

So can anyone suggest me on how to do this?

所以有人可以建议我如何做到这一点?

1 个解决方案

#1


2  

select
'UPDATE  mt
SET ' + ID_F + ' = ac.' + ID_F + '
FROM Ms.AT.AT_CRAW t
INNER JOIN ' + M_Type + ' ac ON t.' + SF1 + '=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt 
ON mt.[SRID] = t.[RID]' as SQL
from Col.TMap.T_Mp

#1


2  

select
'UPDATE  mt
SET ' + ID_F + ' = ac.' + ID_F + '
FROM Ms.AT.AT_CRAW t
INNER JOIN ' + M_Type + ' ac ON t.' + SF1 + '=SV1
AND ac.ID = 1
INNER JOIN Ms.AT.AT_CRAW_Dmtemp mt 
ON mt.[SRID] = t.[RID]' as SQL
from Col.TMap.T_Mp