2015-02-10 84 views
0

我在SQL Server 2008表中有一個XML列。我想要做的是爲我的存儲過程提供一個給定的參數去掉參數中的任何空格(使用REPLACE),並在WHERE條件中使用這個參數,但是接下來使用XQuery存在子句也可以在xml數據上使用REPLACE方法:在SQL Server中使用替換條件查詢XML數據

-- Add the parameters for the stored procedure here 
@PostCode varchar(20) = '' 
AS 
BEGIN 
    -- strip out any spaces from the post code param 
    SET @PostCode = REPLACE(@PostCode, ' ','') 

    SELECT TOP 1 * 
    FROM sd_LocalAuthorities 
    WHERE PostCodes.exist(N'REPLACE(/PostCodes/PostCode/text(), '' '','''')[. = sql:variable("@PostCode")]') = 1 
END 

我得到了錯誤的XQuery的sd_LocalAuthorities.PostCodes.exist()

沒有功能「{} http://www.w3.org/2004/07/xpath-functions:REPLACE()

運行該程序時。有沒有其他REPLACE()我可以使用這個WHERE標準去掉空格,我不想修改表本身。

+0

存在函數需要XQuery表達式作爲參數,而不是T-SQL函數。工作,但*效率不高的方法是將PostCodes轉換爲varchar,替換雙空格並轉換爲xml。 – EKOlog 2015-02-10 14:58:33

+0

感謝您指示我試過這個,就像您說它效率不高,需要10秒鐘才能運行查詢 – user3783297 2015-02-10 15:10:19

回答

0

有一個XQuery函數'replace',但是它在您想要使用它的TSQL中不可用。作爲一種替代方法,您可以將該郵件從XML中提取出來,並替換原始值。像這樣的東西;

declare @sd_LocalAuthorities table (id int, postcodes xml) 
declare @PostCode varchar(20); set @PostCode = 'BB11BB' 

insert @sd_LocalAuthorities values (1, N'<PostCodes><PostCode>AA1 1AA</PostCode></PostCodes>') 
insert @sd_LocalAuthorities values (2, N'<PostCodes><PostCode>BB1 1BB</PostCode></PostCodes>') 
insert @sd_LocalAuthorities values (3, N'<PostCodes><PostCode>CC1 1CC</PostCode></PostCodes>') 

select top 1 
    la.* 
from 
    @sd_LocalAuthorities la 
     cross apply la.postcodes.nodes('/PostCodes/PostCode') as t(c) 
where 
    replace(t.c.value('.', 'varchar(20)'), ' ', '') = @PostCode 

該方法比將整個XML文檔/碎片轉換爲varchar更精確,因爲它只對郵編值執行替換。根據您的情況,XML索引可能有助於提升性能。

+0

非常感謝,儘管令人驚訝的是它只比將列轉換爲Varchar(Max)更有效替換然後轉換回xml。 – user3783297 2015-02-10 15:21:00