One of the possible ways to paste UniqueIdentifier into text string is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Declare @lId UniqueIdentifier = NewId()
Declare @x NVarChar(Max) =
	N'
	Select
		[id]
	From
		[table]
	Where
		[column] = '+IsNull(N'N'''+Cast(@lId As NVarChar(64))+'''', 'Null')
Print @x
/*
	Select
		[id]
	From
		[table]
	Where
		[column] = N'094FDFB4-7665-4E6A-89E0-B6A6C231D617'
*/

If Null is in the variable, the output will be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Declare @lId UniqueIdentifier
Declare @x NVarChar(Max) =
	N'
	Select
		[id]
	From
		[table]
	Where
		[column] = '+IsNull(N'N'''+Cast(@lId As NVarChar(64))+'''', 'Null')
Print @x
/*
	Select
		[id]
	From
		[table]
	Where
		[column] = Null
*/
Share

Leave a Reply