Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXEC in T-SQL ignores CONCAT_NULL_YIELDS_NULL

Tags:

sql

sql-server

With any version of Sql Server, I cannot understand why, in the following script, EXEC returns the result of GetDate(). I expected no result.

SET CONCAT_NULL_YIELDS_NULL ON;
DECLARE @sql_select  nvarchar(150) = 'SELECT GetDate()';
DECLARE @sql_select2 nvarchar(150) = NULL;
SELECT  @sql_select + @sql_select2
EXEC(@sql_select + @sql_select2)
like image 472
ildanny Avatar asked Oct 29 '22 21:10

ildanny


1 Answers

I think, inside exec, NULL is converted into empty string. Here is an easier example

DECLARE @sql_select2 varchar(200) ;

exec('select 1' + @sql_select2) 

returns 1 though it is concatenated with a NULL value.

But when we do the concatenation outside it works as expected.

DECLARE @sql_select NVARCHAR(150) = 'SELECT GetDate()';
DECLARE @sql_select2 NVARCHAR(150) = NULL;
DECLARE @sql VARCHAR(500)

SET @sql = @sql_select + @sql_select2

EXEC(@sql) 

returns nothing

like image 196
Pரதீப் Avatar answered Nov 15 '22 05:11

Pரதீப்