Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't SQL Server's OBJECT_ID(NVARCHAR) take a variable?

So why doesn't this work?

<!-- language: lang-sql -->
    DECLARE @tn NVARCHAR
    SET @tn = 'MyTable'
    SELECT OBJECT_ID(@tn)

When this does:

<!-- language: lang-sql -->
    SELECT OBJECT_ID('MyTable')

I need to pass a variable into this function.

like image 613
davesbrain Avatar asked May 09 '26 15:05

davesbrain


2 Answers

It does.

declare @name sysname = N'sys.objects';
select object_id(@name);


-----------
-385

(1 row(s) affected)

In your example you declare a variable of length 1 (since you omit the length). OBJECT_ID(N'M') finds nothing and returns NULL.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

like image 181
Remus Rusanu Avatar answered May 11 '26 06:05

Remus Rusanu


Your problem is that you're missing the size on your NVARCHAR.

This works:

DECLARE @tn NVARCHAR(20)
SET @tn = 'MyTable'
SELECT OBJECT_ID(@tn)
like image 33
Jerad Rose Avatar answered May 11 '26 04:05

Jerad Rose