我有SP我调用以下示例 (调用不是来自SQL,而是来自.net程序)
或
-- run with a few grantees
exec someproc 99999, '<grantees><grantee id="99"/><grantee id="100"/><grantee id="101"/></grantees>'
-- takes about 1 sec with > 59s on xml decomp
或者
-- run with lots of grantees (approx 2000)
exec someproc 99999, '<grantees><grantee id="99"/><grantee id="100"/>....<grantee id="2001"/></grantees>'
-- takes about 5 sec with > 4s on xml decomp
或者
-- run with mega loads of grantees (approx 12000)
exec someproc 99999, '<grantees><grantee id="99"/><grantee id="100"/>....<grantee id="12001"/></grantees>'
-- takes about 1 min with > 59s on xml decomp
而且我发现 xml分解是最慢的部分(在每种情况下大约96%的查询 - 并且相信我在插入/删除/更改吨数据其余的过程)。
如果我分解XML的方式是给定输入集的最佳方式,我很好奇。 我使用XML的标准只是简单地传递SP一些整数 - 所以感谢任何有关更好方法的建议。
create procedure someproc(@id int, @users xml = '<grantees/>') as
begin
-- decompose the users into a row set
declare @allUsers table (
id int
)
insert into @allUsers (id)
select distinct grantee.value('@id', 'int') uno
from @users.nodes('/grantees/grantee') grantees(grantee)
where isnull(grantee.value('@id', 'int'), 0) > 0
select * from @allUsers
-- other stuff happens
end
答案 0 :(得分:2)
由于您无法使用表参数,请尝试传入CSV sting并让存储过程将其拆分为行。
在SQL Server中分割字符串的方法有很多种。本文涵盖几乎所有方法的PRO和CON:
您需要创建拆分功能。这就是如何使用拆分功能:
SELECT
*
FROM YourTable y
INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value
I prefer the number table approach to split a string in TSQL但是有很多方法可以在SQL Server中拆分字符串,请参阅上一个链接,该链接解释了每个链接的PRO和CON。
要使Numbers Table方法起作用,您需要进行一次性表设置,这将创建一个包含1到10,000行的表Numbers
:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
设置Numbers表后,创建此拆分功能:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
@SplitOn char(1) --REQUIRED, the character to split the @List string on
,@List varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
( ----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT @SplitOn + @List + @SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = @SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
);
GO
现在,您可以轻松地将CSV字符串拆分为表格并加入其中,或者根据需要使用它:
CREATE PROCEDURE YourProcedure
(
@CSV_Param varchar(1000)
)
AS
--just an example of what you can do
UPDATE t
SET Col1=...
FROM dbo.FN_ListToTable(',',@CSV_Param) dt
INNER JOIN TBL_USERS t ON CAST(dt.value AS INT)=t.id
GO
只需从适用于大量CSV的文章(CLR,循环,无论如何)中选择最佳字符串拆分功能,您就可以获得更好的性能。
答案 1 :(得分:0)
如果您所做的只是从元素集合中提取单个字段,那么通过简单地将XML解析为字符串,将字段提取到数组中并将数组传递给SP或者将值插入临时表并将表的名称传递给SP。无论哪种方式,您都没有解析XML的数据库引擎。这种方法不是最灵活的,因此如果您需要为几种不同类型的元素执行此操作,则可能不合适。