Pergunta

For example, I need to select all of one user's file's ids and use those ids in several updates in a row. Is there a way to use WITH in multiple updates other than copying and pasting it into each update query?

Foi útil?

Solução

No, it's not really possible. See this link (for TSQL):

This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, MERGE, or DELETE statement.

In PostgreSQL, it is the same (see here):

These statements, which are often referred to as Common Table Expressions or CTEs, can be thought of as defining temporary tables that exist just for one query.

Simplest way to change WITH to make it work with more queries would be rewriting it to SELECT INTO queries:

SELECT a,b,c
INTO #TemporaryTable
WHERE a<>b

(do something)

DROP TABLE #TemporaryTable

Outras dicas

Are you running all your UPDATE queries in a single stored procedure / transaction? If so, just write the results of your CTE to a temp table (or a table variable, if you're savvy - but then they're harder to debug - ahh well) for re-use and then drop it when you're done. Sure you'll suffer a teensy bit of IO performance but it'll keep your code a lot cleaner. It's basically what temp tables are for - intermediate data storage.

Are you sure this wouldn't work?(from the link above, or http://msdn.microsoft.com/en-us/library/ms175972.aspx)

WITH Parts(AssemblyID, ComponentID, PerAssemblyQty, EndDate, ComponentLevel) AS
(
    SELECT your data ....
)
UPDATE Production.BillOfMaterials
SET PerAssemblyQty = c.PerAssemblyQty * 2
FROM Production.BillOfMaterials AS c
JOIN Parts AS d ON     c.ProductAssemblyID = d.AssemblyID
WHERE d.ComponentLevel = 0; 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top