DYNAMIC SQL

Why is this returning a blank screen?

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName> 
DECLARE
@numRecordsToProcess INT, 
@RemoteServer VARCHAR(50)
--AS
--BEGIN

SET NOCOUNT ON;

DECLARE @StrSql VARCHAR(6000)

SET @numRecordsToProcess = 0



IF @numRecordsToProcess != 0
BEGIN
SET @strSql =   N'SELECT DISTINCT TOP ' + convert(varchar(9), @numRecordsToProcess) + ' ' + '
i.[MasterKey], 
i.[OriginalKey], 
i.[ImageName], 
i.[ImageBatchType], 
i.[NoOfPages],  
i.[ImageSize], 
i.[Station], 
i.[UserId], 
i.[ServerPath], 
i.[Path], 
i.[Status], 
i.[VirtualPath], 
i.[LocalImageRootPath], 
i.[GroupKey], 
dt.[TypeKey] AS [DocumentType]
                        FROM [ImageMaster] i(NOLOCK) 
                            INNER JOIN [ImagePage] ip(NOLOCK) ON i.[MasterKey] = ip.[MasterDocument] 
                            INNER JOIN DocumentTypes dt(NOLOCK) ON ip.PageType = dt.TypeKey 
                        WHERE i.[CreateDateTime] >= DATEADD(Year,-2,GETDATE()) 
                            AND NOT EXISTS 
(SELECT [MasterKey] 
                                FROM ['+@RemoteServer+'].[Interact].[dbo].[tblImageTransfer3xLogging] lg (NOLOCK)
                                WHERE i.[MasterKey] = lg.[MasterKey] AND lg.[Processed] = ''Y'')'
END
ELSE
BEGIN 
SET @strSql =   N'SELECT DISTINCT TOP ' + convert(varchar(9), @numRecordsToProcess) + ' ' + '
i.[MasterKey], 
i.[OriginalKey], 
i.[ImageName], 
i.[ImageBatchType], 
i.[NoOfPages],  
i.[ImageSize], 
i.[Station], 
i.[UserId], 
i.[ServerPath], 
i.[Path], 
i.[Status], 
i.[VirtualPath], 
i.[LocalImageRootPath], 
i.[GroupKey], 
dt.[TypeKey] AS [DocumentType]
                        FROM [ImageMaster] i(NOLOCK) 
                            INNER JOIN [ImagePage] ip(NOLOCK) ON i.[MasterKey] = ip.[MasterDocument] 
                            INNER JOIN DocumentTypes dt(NOLOCK) ON ip.PageType = dt.TypeKey 
                        WHERE i.[CreateDateTime] >= DATEADD(Year,-2,GETDATE()) 
                            AND NOT EXISTS 
(SELECT [MasterKey] 
                                FROM ['+@RemoteServer+'].[Interact].[dbo].[tblImageTransfer3xLogging] lg (NOLOCK)
                                WHERE i.[MasterKey] = lg.[MasterKey] AND lg.[Processed] = ''Y'')'
END

PRINT @StrSql
EXEC (@StrSql)


  • Edited by soldierfc 11 hours 27 minutes ago
September 4th, 2015 3:44pm

Because you never declared @RemoteServer variable, so it's NULL. Also, as I said in your previous thread, your second part should start from

SET @strSql =   N'SELECT DISTINCT i.[MasterKey], 

unless you want to generate SELECT DISTINCT TOP 0 ... 

which I don't think is a valid statement.

Also, declare your variable as nvarchar(max) and not as varchar

Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 3:54pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics