Profilo di Ashish"Getting better never st...FotoBlogElenchiAltro ![]() | Guida |
|
20 settembre SQL Server –Error - The FOR XML clause is not allowed in a INSERT statement. - Returning the result of a FOR XML, ELEMENTS in a dynamic query to a variableProblem :- When you try to execute a dynamic query having the FOR XML AUTO like this (ignore the query itself for now, you can find the complete script at the end of this article):- DECLARE @Data2 TABLE(col xml) You get an error like the following "The FOR XML clause is not allowed in a INSERT statement.” From http://msdn.microsoft.com/en-us/library/aa226520(SQL.80).aspx:- The above is applicable for SQL server 2005 as well. Very annoying… However, if you have something like below, the query would get executed successfully:- SELECT @Query= 'SELECT ( SELECT Customer.CustomerID,Address.FullAddress,Phone.PhoneNumberFROM #tempCustomer Customer JOIN #tempAddress Address ON Address.CustomerID= Customer.CustomerID JOIN #tempPhone Phone ON Phone.CustomerID= Customer.CustomerID FOR XML AUTO, ELEMENTS ) '
Notice that I prefixed the query with ‘SELECT(‘ and suffixed it with ‘)’. This would allow the query to execute but to return the data in text format rather than XML. However, you can have the result stored in a column of XML data type of a temporary table/variable and It would appear as if the result was XML. So we need to stuff the prefix and then the suffix in the query. Here is where the STUFF function would come to rescue. It is different from REPLACE function as it allows you to replace a specific instance of a character for a length. The complete query :- (Just run it) /* Temporary table to hold sample data. Forgive me for not using the table variable as they would be out of scope when I would use them in the dynamic query*/
if OBJECT_ID('tempdb..#tempPhone') is not null /* Insert sample data*/ /* Build the dynamic query*/ /* There can be many 'SELECT' in the query, we need to get the last one as that would be the one CommentiPer aggiungere un commento, accedi con il tuo Windows Live ID (se utilizzi Hotmail, Messenger o Xbox LIVE possiedi già un Windows Live ID). Accedi Non hai ancora un Windows Live ID? Registrati RiferimentiL'URL di riferimento per questo intervento è: http://ashishrocks.spaces.live.com/blog/cns!BED6CE34F24CB429!407.trak Blog che fanno riferimento a questo intervento
|
|
|