Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 monday morning brain cramp

Author  Topic 

jholovacs
Posting Yak Master

163 Posts

Posted - 2007-10-29 : 10:53:51
Can someone tell me why this returns a null value? I'm trying to troubleshoot why the sql isn't working; I can't even seem o get the sql to show up. I know it's something simple and stupid, but hell if I can figure out what it is.


DECLARE @sql NVARCHAR(MAX),
@originalInstance sysname,
@OriginalName sysname;

SET @originalInstance = CAST('production' AS sysname);
SET @originalname = CAST('warehouse' AS sysname);


SET @sql = '
SELECT *
INTO #Backups
FROM OPENQUERY(' + QUOTENAME(@OriginalInstance) + ', ' + QUOTENAME('
SELECT
a.backup_start_date,
a.backup_finish_date,
c.file_type,
c.logical_name,
c.physical_name,
b.physical_device_name,
a.position
FROM
msdb.dbo.backupset a WITH (NOLOCK)
INNER JOIN
msdb.dbo.backupmediafamily b WITH (NOLOCK)
ON a.media_set_id = b.media_set_id
INNER JOIN
msdb.dbo.backupfile c WITH (NOLOCK)
ON a.backup_set_id = c.backup_set_id
WHERE
a.database_name = ' + QUOTENAME(@OriginalName, '''') + '
AND
a.backup_set_id >=
(
SELECT MAX(d.backup_set_id)
FROM msdb.dbo.backupset d
WHERE
d.TYPE = ' + QUOTENAME('D', '''') + '
AND
d.database_name = ' + QUOTENAME(@OriginalName, '''') + '
AND
d.backup_finish_date IS NOT NULL
)
AND
c.backup_size > 0
AND
a.backup_finish_date IS NOT NULL
ORDER BY
a.backup_set_id, c.file_type;', '''') + ');

SELECT * FROM #Backups;
';

select @sql;



___________________________
Geek At Large

klo
Starting Member

7 Posts

Posted - 2007-10-29 : 14:12:10
QUOTENAME will return an nvarchar of 258 - your string is too long. Its croaking somewhere around the "b.physical_device_name,"
where the length of your string exceeds 129 (258/2 = 129) e.g.

SELECT LEN(' SELECT
a.backup_start_date,
a.backup_finish_date,
c.file_type,
c.logical_name,
c.physical_name,
b.physical_device_name,
')

Therefore the QUOTENAME is returning a null. And as a NULL + any string = NULL your result is a NULL. If you want to see the output of your string where nulls are treated as "" just set the following ...

SET CONCAT_NULL_YIELDS_NULL OFF

This is handy for debugging but you should switch it back ON ( the sql server default) when finished as otherwise you could be handling NULLS unbeknownst to your good self

Ok?
Go to Top of Page
   

- Advertisement -