Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to concatenate uniqueidentifier in a dynamic query

I have a dynamic query in which I want to concatenate uniqueidentifier, but + and & operators are not supporting this, is there a way I can concatenate uniqueidentifier to a dynamic string. Any sample or any help in this regard will be highly appricated.

like image 374
Yaser Ahmed Avatar asked Jun 24 '09 05:06

Yaser Ahmed


People also ask

What is the Uniqueidentifier datatype in SQL?

Uniqueidentifier is a Microsoft SQL Server data type that is used to store Globally Unique Identifiers (GUIDs). It can store 16 bytes of data. The Developer tool treats the Uniqueidentifier data type as String.

How do I get Uniqueidentifier in SQL Server?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.

What is dynamic query in SQL with example?

For example, dynamic SQL lets you create a procedure that operates on a table whose name is not known until runtime. In past releases of Oracle, the only way to implement dynamic SQL in a PL/SQL application was by using the DBMS_SQL package.


2 Answers

Have you tried casting or converting to a string first, then concating?

CAST(NEWID() AS NVARCHAR(36))
like image 181
Frank Krueger Avatar answered Sep 22 '22 07:09

Frank Krueger


I know this is old but I ran into this post trying to figure out the same thing and the problem was that I didn't have enough 's around my unique identifier. I basically had:

'SELECT * FROM Interface WHERE ID = '' + CAST(@InterfaceID AS NVARCHAR(36)) + '' AND 1 = 1'

I got an error saying incorrect syntax near 00A (the first part of the GUID). The problem is that this was parsing to :

SELECT * FROM Interface WHERE ID = 00A3F5B5-C7B3-4128-B03A-EADE79129F40 AND 1 = 1

By changing my query to:

'SELECT * FROM Interface WHERE ID = ''' + CAST(@InterfaceID AS NVARCHAR(36)) + ''' AND 1 = 1'

with three apostrophes I got:

SELECT * FROM Interface WHERE ID = '00A3F5B5-C7B3-4128-B03A-EADE79129F40' AND 1 = 1

Which is correct.

Hope that helps.

like image 31
jesse Avatar answered Sep 22 '22 07:09

jesse