简体   繁体   中英

Recieving error when updating with subquery within SSMS

I've run into an error where my subquery returns more values than the permitted "1".

I'm trying to update Table [I] with the.QUERY value from Table [P].

Both tables are from different databases. They have the same value in column ID. And I want to try out ID's 100-150 as a test first.

UPDATE I 
    SET I.metadata02 = (SELECT CAST([XML]AS xml)
                            .query(N'/inkoopfacturen/inkoopfactuur/jaar')
                            .value('.', 'varchar(30)') 
                    FROM [Archive190404132717].[dbo].[tblArchiveInvoices])    
FROM tblindex AS I 
    INNER JOIN [Archive190404132717].[dbo].[tblArchiveInvoices] AS P 
        ON  I.ID = P.ID    
WHERE 
    I.tasknumber BETWEEN '100' and '150'

OK, seems like what you are actually after is actually just this:

UPDATE I
SET I.metadata02 = CAST([XML] AS xml).query(N'/inkoopfacturen/inkoopfactuur/jaar').value('.', 'varchar(30)')
FROM tblindex I
     INNER JOIN [Archive190404132717].[dbo].[tblArchiveInvoices] P ON I.ID = P.ID
WHERE I.tasknumber BETWEEN '100' AND '150';

There's no need for the subquery, and the 2nd reference to tblArchiveInvoices ; you've already joined to it.

Why are you using both a subquery and join ? I assume you want a correlated subquery:

UPDATE I 
    SET I.metadata02 = (SELECT CAST([XML]AS xml)
                               .query(N'/inkoopfacturen/inkoopfactuur/jaar')
                               .value('.', 'varchar(30)') 
                        FROM [Archive190404132717].[dbo].[tblArchiveInvoices]
                        WHERE I.ID = P.ID  
                       )
FROM tblindex I 
WHERE I.tasknumber BETWEEN '100' and '150';

Also, a field called tasknumber should really be stored as a number. The comparison as strings can be misleading. If it is a number, drop the single quotes. If it is a string, you should realize that '10001 meets the WHERE conditions.

maybe you're trying something like this:

UPDATE I 
SET metadata02 = X
FROM tblindex AS I 
INNER JOIN (SELECT Id, CAST([XML]AS xml).query(N'/inkoopfacturen/inkoopfactuur/jaar').value('.', 'varchar(30)') AS X
            FROM [Archive190404132717].[dbo].[tblArchiveInvoices] ) AS P 
            ON  I.ID = P.ID    
WHERE I.tasknumber BETWEEN '100' and '150'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM