I just re-read your question before posting this. While this technique probably can't be directly applied to .net, you might be able to work out something similar. So:
I've recently had to do a lot of dynamic coding in T-SQL, and I've come up with the following routine. Assume you've got a chunk of code like so:
DECLARE
@Command nvarchar(max)
,@SearchFor int
SET @Command = 'SELECT * from MyTable where PrimaryKey = @SearchFor'
SET @SearchFor = 1
EXECUTE sp_executesql
@Command
,N'@SearchFor int'
,@SearchFor
This is of course very simplisitc--if you need to do dynamic code, you're going to have complex to wildly complex queries, and as you've discovered these can be very difficult to debug. Here's how I'd rewrite the above code:
DECLARE
@Command nvarchar(max)
,@SearchFor int
,@Debug int
-- 0 = Run it
-- 1 = Run and display it
-- 2 = Display it
SET @Command = 'SELECT * from MyTable where PrimaryKey = @SearchFor'
SET @SearchFor = 1
SET @Debug = 1
IF @Debug > 0
-- Show the command that would be run
PRINT replace(@Command, '@SearchFor', cast(@SearchFor as varchar(10)))
IF @Debug < 2
-- Run it
EXECUTE sp_executesql
@Command
,N'@SearchFor int'
,@SearchFor
This is extra code to write and debug, but once it's in place and working it can be invaluable in debugging situations. If it's part of a stored procedure, make @Debug a parameter that defaults to 0, and make sure that if set to 2, the procedure doesn't actually do anything.