Question

For example:

-- Directly with a DML Statement
WITH CTE_DML AS
(
    UPDATE Table1
    SET Column1 = 'Value1'
    FROM Table1
)

-- Indirectly by executing a procedure
WITH CTE_SP AS
(
    EXEC sp_ProcedureThatModifiesTheDatabaseState
)

-- Some kind of cross applied function
WITH CTE_FN AS
(
    SELECT Table1.Column1
    FROM Table1
    CROSS APPLY fn_FunctionThatModifiesTheDatabaseState(Table1.Column2)
)

I know none of these are valid (and frankly objectively stupid - especially the function) but that's kind of my question. I only know a subset which is what's not possible when it comes to modifying the database state within the scope of a CTE. Is there any way to modify the database state, e.g. a table, from within the scope of a CTE?

Was it helpful?

Solution

Practically, no.

Technically, yes, but you have to try really hard and have really bad security in place. For example (untested, just for the general idea):

CREATE FUNCTION dbo.BadIdea()
RETURNS int
AS
BEGIN
  DECLARE @sql nvarchar(max);
  SET @sql = 'osql -S' +@@servername +' -E -q "UPDATE db.dbo.table... ;"';
  EXEC master.sys.xp_cmdshell @sql;
  RETURN 1;
END
GO

;WITH badIdeaCTE AS 
(
  SELECT x = dbo.BadIdea() FROM sys.all_objects
)
SELECT x FROM badIdeaCTE;

There are other ways I think involving OPENQUERY or OPENROWSET. But generally unless you've set the table specifically to take advantage of these hacks, it's not happening.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top