根据条件将值从另一个 table 插入到 table

Insert values to a table from another table based on condition

所以我有一个 SQL table,我在其中通过连接其他列并输入来自 table 的列值来输入值。

CREATE TABLE #temp_t (id INT, cname NVARCHAR(100), val INT, aid INT)
INSERT INTO #temp_t 
SELECT DISTINCT
ISNULL(IDXC.id, 0) id, sg.name + '-webApp' cName, 0 val, ag.ID aid
FROM spgroup sg
JOIN APPA APP ON sg.id > 1 AND sg.val & 4 = 0 AND APP.dagi = sg.id 
JOIN AIDBI XDI ON APP.bs = XDI.bsid
LEFT JOIN #IDXC ON IDXC.agpv = sg.id
WHERE IDXC.id IS NULL

现在,在向 table 中插入值时,我需要检查 sg.name 是否存在于 sysName table 中,如果存在,则需要替换 -webApp通过 -andApp 否则它仍然是 -webApp

我怎样才能这样做?

您可以在 CASE 表达式中使用 EXISTS

SELECT DISTINCT COALESCE(i.id, 0) as id,
       (sg.name +
        (CASE WHEN EXISTS (SELECT 1 FROM sysname sn WHERE sn.name = sg.name)
              THEN '-andApp' ELSE '-webApp'
         END)
       )  as cName,
       0 as val, ag.ID as aid
FROM spgroup sg JOIN
      APPA APP 
      ON sg.id > 1 AND (sg.val & 4) = 0 AND APP.dagi = sg.id  JOIN
      AIDBI XDI 
      ON APP.bs = XDI.bsid LEFT JOIN
      #IDXC i
      ON i.IDXCsgpv = sg.id
WHERE i.id IS NULL