【发布时间】:2015-01-03 07:11:57
【问题描述】:
显然我太习惯于过程式编程,我不知道如何使用基于集合的方法来处理这个问题。
我在 SQL Server 中有几个临时表,每个表都有数千条记录。其中一些每个都有数万条记录,但它们都是记录集的一部分。我基本上是在加载一堆看起来像这样的 xml 数据:
<root>
<entry>
<id-number>12345678</id-number>
<col1>blah</col1>
<col2>heh</col2>
<more-information>
<col1>werr</col1>
<col2>pop</col2>
<col3>test</col3>
</more-information>
<even-more-information>
<col1>czxn</col1>
<col2>asd</col2>
<col3>yyuy</col3>
<col4>moat</col4>
</even-more-information>
<even-more-information>
<col1>uioi</col1>
<col2>qwe</col2>
<col3>rtyu</col3>
<col4>poiu</col4>
</even-more-information>
</entry>
<entry>
<id-number>12345679</id-number>
<col1>bleh</col1>
<col2>sup</col2>
<more-information>
<col1>rrew</col1>
<col2>top</col2>
<col3>nest</col3>
</more-information>
<more-information>
<col1>234k</col1>
<col2>fftw</col2>
<col3>west</col3>
</more-information>
<even-more-information>
<col1>asdj</col1>
<col2>dsa</col2>
<col3>mnbb</col3>
<col4>boat</col4>
</even-more-information>
</entry>
</root>
下面是临时表的简要展示:
临时表1(条目):
+------------+--------+--------+
| UniqueID | col1 | col2 |
+------------+--------+--------+
| 732013 | blah | heh |
| 732014 | bleh | sup |
+------------+--------+--------+
临时表 2(更多信息):
+------------+--------+--------+--------+
| UniqueID | col1 | col2 | col3 |
+------------+--------+--------+--------+
| 732013 | werr | pop | test |
| 732014 | rrew | top | nest |
| 732014 | 234k | ffw | west |
+------------+--------+--------+--------+
临时表 3(更多信息):
+------------+--------+--------+--------+--------+
| UniqueID | col1 | col2 | col3 | col4 |
+------------+--------+--------+--------+--------+
| 732013 | czxn | asd | yyuy | moat |
| 732013 | uioi | qwe | rtyu | poiu |
| 732014 | asdj | dsa | mnbb | boat |
+------------+--------+--------+--------+--------+
我正在从一个 XML 文件加载这些数据,并且发现这是我可以分辨哪些信息属于哪条记录的唯一方法,因此每个临时表的顶部都插入了以下内容:
T.value('../../id-number[1]', 'VARCHAR(8)') UniqueID,
如您所见,每个临时表都有一个UniqueID 分配给它的特定记录,以表明它属于主记录。我在数据库中有大量项目,我想使用基于集合的方法更新每个非临时表中的每一列,但它必须受到UniqueID 的限制。
在第一个以外的表中,有一个基于主表的PrimaryKey_ID 的Foreign_ID,并且不会插入UniqueID……只是为了帮助告诉什么去哪里。
这是我试图弄清楚的确切逻辑:
如果
id-number当前存在于主表中,则根据主表的PrimaryKey_ID编号更新表,该编号与每个表的Foreign_ID中的确切编号相同。外键表的编号与id-number完全不同——它们不一样。如果
id-number不存在,则插入记录。我已经完成了这部分。
但是,我目前的思维定势是我必须设置临时变量,例如@IDNumber 和@ForeignID,然后循环遍历它。我不仅得到了多个结果而不是当前结果,而且每个人都说不应该使用WHILE,尤其是对于如此大量的数据。
如何使用基于集合的方法更新这些表?
【问题讨论】:
-
XML 是否已经提取到临时表中(即以“#”开头)?
-
是的。 #TempTable1、TempTable2 等等。其中有 15 个。
标签: sql-server xml