English 中文(简体)
SQL 优化:XML 或分隔字符串
原标题:Sql Optimization: Xml or Delimited String

希望这只是一个简单的问题,涉及到Sql 2008查询的性能优化。

我曾为那些在其ETL过程和部分网站中广泛使用Stored Procs的公司工作。我见过需要根据有限一组关键值检索特定记录的情况。下面是伪代码所示的三种不同处理方式。

动态SQL将字符串连接在一起并执行。

EXEC( SELECT * FROM TableX WHERE xId IN (  + @Parameter +  ) 

使用用户定义的函数将分隔字符串拆分成表格。

SELECT * FROM TableY INNER JOIN SPLIT(@Parameter) ON yID = splitId

使用XML作为参数,而不是限定的varchar值

SELECT * FROM TableZ JOIN @Parameter.Nodes(xpath) AS x (y) ON ...

尽管我知道在第一个片段中创建动态SQL是一个不好的想法,原因众多,但是我的好奇心来自最后两个示例。在我的代码中通过XML传递此类列表是否更有效,就像片段3中一样,还是最好仅限制值并使用udf来处理它?

最佳回答

现在有第四个选择 - 表值参数,可以将一张值表作为参数传递到存储过程中,然后像普通表变量一样使用。我更喜欢这种方法而不是 XML(或 CSV 解析方法)。

我不能引用所有不同方法之间的性能数据,但这是我要尝试的一个——我建议对它们进行一些真实的性能测试。

Edit:
A little more on TVPs. In order to pass the values in to your sproc, you just define a SqlParameter (SqlDbType.Structured) - the value of this can be set to any IEnumerable, DataTable or DbDataReader source. So presumably, you already have the list of values in a list/array of some sort - you don t need to do anything to transform it into XML or CSV.

我认为这也使得存储过程更清晰、简单且易于维护,提供了一种更自然的实现终结果的方式。其中一个主要点是SQL在处理基于集合、非循环、非字符串操作的活动时表现最佳。

这并不意味着它对传递的大量值的表现会很好。但对于较小的集合(最多约1000个),它应该可以接受。

问题回答

使用UDF调用比使用内置函数拆分XML成本稍高。

然而,这只需要在每个查询中执行一次,因此性能差异将可以忽略不计。





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

难以执行 REGEXP_SUBSTR

I m 查询Oracle 10g。 我有两张表格(样本数据见下文)。 i m 试图提取一些领域

SQL Query Shortcuts

What are some cool SQL shorthands that you know of? For example, something I learned today is you can specify to group by an index: SELECT col1, col2 FROM table GROUP BY 2 This will group by col2

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

OracleParameter and DBNull.Value

we have a table in an Oracle Database which contains a column with the type Char(3 Byte). Now we use a parameterized sql to select some rows with a DBNull.Value and it doesn t work: OracleCommand ...

Running numbers in SQL

I have a SQL-statement like this: SELECT name FROM users WHERE deleted = 0; How can i create a result set with a running number in the first row? So the result would look like this: 1 Name_1 2 ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签