Question

So I have found plenty of examples across SO that show how to assign the result of dynamic SQL to variables but I have yet to find one that does it the way that I am trying to... So either I am going about this the wrong way or I just haven't found the proper syntax to perform this correctly.

Basically, I am trying to create an XML record of a row from a table before deleting the row from the table (think of it as an audit of the table) using a Stored Procedure. I was attempting to do this through dynamic SQL so that the Stored Procedure can be called from multiple other Stored Procedures that perform Delete operations on their corresponding tables, but before doing so they pass the necessary information (the @sql variable which will contain the select statement to obtain the record) to this Audit Stored Procedure.

Create Procedure dbo.AuditDelete(
@sql NVARCHAR(200),
@TableName VARCHAR(50),
@UserName NVARCHAR(256)
)
AS
  DECLARE @XML XML
BEGIN
  --at this point @sql will contain a select statement written by the calling stored procedure
  --which is specifically written to return the record that is being deleted, example:
@sql = select * from my.table where tableId = 1 FOR XML AUTO

  execute sp_executesql @sql, N'@XML XML OUTPUT', @XML = XML OUTPUT;
  SELECT @XML 
              --I was doing this as a check to ensure that XML has the record
              --because the execute command returned the XML record, but @XML is null...
              --and I can't figure out why

  --code for inserting into the Audit table

So I'm sure that its either some syntax I'm missing or perhaps I'm just going about this the wrong way. Any suggestions?

Note: this is being done in SSMS on SQL Server 2008 R2

Was it helpful?

Solution

You need to assign the result your query to the parameter in the dynamic SQL.

set @sql = N'set @XML = (select * from my.table where tableId = 1 FOR XML AUTO)'
execute sp_executesql @sql, N'@XML XML OUTPUT', @XML OUTPUT
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top