如何根据查询更新SQL Server表中的字符串?

时间:2016-02-02 17:46:34

标签: sql sql-server

我有两张表ABA有一个Id和一个字符串,其中包含一些未显示的表C中的某些文本和ID的嵌入信息

Aid| AString
 1   "<thing_5"><thing_6">"
 2   "<thing_5"><thing_6">"

 Bid|Cid|Aid
  1   5   1
  2   6   1
  3   5   2
  4   6   2

我意识到这是一种疯狂的结构,但这就是生活。

我需要更新A中的字符串,以便Cid代替Bid,而不是AidBid相关联配对)

这是否是我应该考虑在SQL中做的事情... A有大约300个条目和B大约1200个所以不是手工做的事

为清楚起见,我希望B保持不变,A最终看起来像这样

Aid| AString
 1   "<thing_1"><thing_2">"
 2   "<thing_3"><thing_4">"

2 个答案:

答案 0 :(得分:1)

此脚本依赖于生成动态SQL语句来更新表,然后执行这些语句。

  • 考虑到cidthing_"内:
  • 首先使用占位符(在这种情况下为cid)替换$$$$$$,以说明cid&{39}和{{1}可能会重叠(例如,更改3> 2和更高版本的2&gt; 1)
  • 然后将占位符更改为正确的bid
bid

结果是:

CREATE TABLE #a(aid INT,astr VARCHAR(MAX));
INSERT INTO #a(aid,astr)VALUES(1,'<thing_5"><thing_6">'),(2,'<thing_5"><thing_6">');

CREATE TABLE #rep(aid INT,bid INT,cid INT);
INSERT INTO #rep(bid,cid,aid)VALUES(5,6,1),(6,5,1),(3,5,2),(4,6,2);

DECLARE @cmd NVARCHAR(MAX)=(
    SELECT
        'UPDATE #a '+
        'SET astr=REPLACE(astr,''thing_'+CAST(r.cid AS VARCHAR(16))+'"'',''thing_$$$$$$'+CAST(r.cid AS VARCHAR(16))+'"'') '+
        'WHERE aid='+CAST(a.aid AS VARCHAR(16))+';'
    FROM
        (SELECT DISTINCT aid FROM #a AS a) AS a
        INNER JOIN #rep AS r ON
            r.aid=a.aid
    FOR 
        XML PATH('')
);
EXEC sp_executesql @cmd;

SET @cmd=(
    SELECT
        'UPDATE #a '+
        'SET astr=REPLACE(astr,''thing_$$$$$$'+CAST(r.cid AS VARCHAR(16))+'"'',''thing_'+CAST(r.bid AS VARCHAR(16))+'"'') '+
        'WHERE aid='+CAST(a.aid AS VARCHAR(16))+';'
    FROM
        (SELECT DISTINCT aid FROM #a AS a) AS a
        INNER JOIN #rep AS r ON
            r.aid=a.aid
    FOR 
        XML PATH('')
);
EXEC sp_executesql @cmd;

SELECT * FROM #a;

DROP TABLE #rep;
DROP TABLE #a;

答案 1 :(得分:0)

您可以使用SQL执行此操作,如下所示。我不清楚c是如何相关的,但你可以根据需要进行调整......

create table a (
Aid int null,
AString varchar(25) null)

insert into a values(1,'"<thing_5"><thing_6">"')
insert into a values(2,'"<thing_5"><thing_6">"')

create table b (
Aid int null,
Bid int null,
Cid int null)

insert into b values(1,1,5)
insert into b values(1,2,6)
insert into b values(2,3,5)
insert into b values(2,4,6)

UPDATE Ax
SET Ax.ASTRING = REPLACE(Ax.ASTRING, 'thing_' + cast(cID as varchar(1)),'thing_' + cast(BID as varchar(1)))
FROM A Ax
INNER JOIN Bx
on ax.Aid=bx.Aid
and Ax.AString like '%thing_' + cast(Cid as varchar(1)) + '%'