Sql request does not print

I am trying to run a dynamic query, but for some odd reason, it is not working. This is not even a seal. Please someone tell me why the next dynamic request is not printing.

DECLARE @CLIENTPK_NEW AS VARCHAR(50)
DECLARE @CGNEEPK AS VARCHAR(50)
DECLARE @TYPE AS VARCHAR(10)

SET @CLIENTPK_NEW='6EF77AAA-1A7B-4D03-A448-D1088DED4134'
SET @CGNEEPK= NULL
SET @TYPE='Mag'

DECLARE @SQL NVARCHAR(MAX)       

SET @SQL = '    
SELECT       
PUBLISHER
FROM CLIENT_SHIPPINGREPORTDATA_FUNCTION('
  + @CLIENTPK_NEW + ' , ' 
  + @CGNEEPK + ' , ' 
  + @TYPE +' )' <=== This is the troubled line, but not sure what is error is.

PRINT  @SQL    <== **Why is this not priniting**

Many thanks

+3
source share
7 answers

As Noel said, this is because you are trying to combine NULL into VARCHAR - the end result will be NULL. You also need to append other varchar values ​​in single quotes to pass them around, which starts to become messy / problematic.

Use parameterized TSQL instead. This will allow you to easily pass NULL to your function, as well as protect against SQL injection.

DECLARE @CLIENTPK_NEW AS VARCHAR(50)
DECLARE @CGNEEPK AS VARCHAR(50)
DECLARE @TYPE AS VARCHAR(10)

SET @CLIENTPK_NEW='6EF77AAA-1A7B-4D03-A448-D1088DED4134'
SET @CGNEEPK= NULL
SET @TYPE='Mag'

DECLARE @SQL NVARCHAR(MAX)       

SET @SQL = '    
SELECT       
PUBLISHER
FROM CLIENT_SHIPPINGREPORTDATA_FUNCTION(
  @CLIENTPK_NEW, @CGNEEPK, @TYPE)'

-- Then to execute it:
EXECUTE sp_executesql @SQL, 
    N'@CLIENTPK_NEW VARCHAR(50), @CGNEEPK VARCHAR(50), @TYPE VARCHAR(10)', 
    @CLIENTPK_NEW, @CGNEEPK, @TYPE
+4
source

(@CGNEEPK), NULL. NULL, . ISNULL(@CGNEEPK, '').

+9

SET @CGNEEPK= '' 
+2

NULL ​​SQL, NULL.

SET @CGNEEPK= NULL

SET @CGNEEPK= ''
+1

@CGNEEPK, NULL. ISNULL @CGNEEPK = ''

SET @SQL = '     
SELECT        
PUBLISHER 
FROM CLIENT_SHIPPINGREPORTDATA_FUNCTION(' 
  + ISNULL(@CLIENTPK_NEW, '') + ' , '  
  + ISNULL(@CGNEEPK, '') + ' , '  
  + ISNULL(@TYPE, '') +' )' 

PRINT  @SQL    <== **Why is this not priniting** 
+1

( ) @TYPE. ( "" ), :

SET @SQL = '    
SELECT       
PUBLISHER
FROM CLIENT_SHIPPINGREPORTDATA_FUNCTION('''
  + @CLIENTPK_NEW + ''' , ''' 
  + isnull(@CGNEEPK, '') + ''' , ''' 
  + @TYPE +''' )'
0

, , :

PRINT '(1) This is ODD, ' + NULL +' very.'
PRINT '(2) This is ODD, ' + ISNULL(NULL,'') +' very.'

:

(2) This is ODD  very.

The entire first line, starting with (1), is omitted!

0
source

Source: https://habr.com/ru/post/1766343/


All Articles