1

I have a table that I want to use into dynamic stored procedure as:

  --Creating table
 DECLARE @SearchKeys AS TABLE(
             DesignKey INT
            )
  --Filling table
 SELECT  pd.DesignKey  FROM [Project] AS [p]
                           LEFT JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
                           LEFT JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
                           INNER JOIN [DesignType] AS [DE] ON [D].
                            WHERE JN.Note LIKE '%'+@JobNote+'%'
                            GROUP BY ParentGuid) JN ON P.ProjectGuid = JN.ParentGuid

Now my table have multiple DesignKeys

Now in my dynamic query I want to do an inner join with this table as:

   DECLARE @Sql NVARCHAR(MAX) = '
            DECLARE @DList TABLE
            (
                            [ProjectKey]         INT
                           , [Project Name]       NVARCHAR(255)
                           ...
            )
   INSERT INTO @DList
                 SELECT
                       [p].[ProjectKey]
                     , [p].[Name] AS [Project Name]
                     ....
                  FROM [Project] AS [p]
                  INNER JOIN '+@SearchKeys+' AS [SK] ON [D].[DesignKey] = [SK].[DesignKey]

But @SearchKeys variable are marked in red and throw

Must declare scalar variable "@SearchKeys"

But I already declared it above query. What am I doing wrong?

Complete code:

               DECLARE @Params NVARCHAR(MAX) = '
      @LastName AS        NVARCHAR(255)
    , @ProjName         NVARCHAR(100)       
    , @RegAbbrv         NVARCHAR(4)  
    , @ProjNum          NVARCHAR(6)  
    , @PostalCode       NVARCHAR(10) 
    , @City             NVARCHAR(255)
    , @AddressLine      NVARCHAR(255)
    , @SortBy       INT          
    , @IncludeArchived  BIT    
    , @IncludeVoided     BIT      
    , @Status           NVARCHAR(255)
    , @JobNote AS       NVARCHAR(255)
    , @Folio   AS        NVARCHAR(255)
    , @DesignType AS      NVARCHAR(255)
    , @Contact AS        NVARCHAR(255)
    , @Customer AS       NVARCHAR(255)
                                '


        DECLARE @SearchKeys AS TABLE(
             DesignKey INT
            )

            INSERT INTO @SearchKeys
            SELECT  pd.DesignKey  FROM [Project] AS [p]
                           LEFT JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
                           LEFT JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
                           INNER JOIN [DesignType] AS [DE] ON [D].[DesignTypeGuid] = [DE].[DesignTypeGuid]
                           LEFT JOIN [General] AS [g] ON [g].[GeneralKey] = [d].[StatusKey]
                           LEFT JOIN [General] AS [h] ON [h].[GeneralKey] = [d].[ShopsStatus]
                           INNER JOIN [Address] AS [a] ON [a].[AddressGuid] = [p].[ProjectGuid]
                           INNER JOIN [Region] AS [re] ON [a].[RegionKey] = [re].[RegionKey]
                           INNER JOIN (SELECT ParentGuid FROM JobNotes JN WITH (NOLOCK) 
                            WHERE JN.Note LIKE '%'+@JobNote+'%'
                            GROUP BY ParentGuid) JN ON P.ProjectGuid = JN.ParentGuid
   DECLARE @Sql NVARCHAR(MAX) = '
            DECLARE @DList TABLE
            (
                            [ProjectKey]         INT
                           , [Project Name]       NVARCHAR(255)
                           , [Project Number]     NVARCHAR(12)
                           , [Design Status]      NVARCHAR(255)
                           , [Design Locked]      BIT
                           , [DesignKey]          INT
                           , [Design Name]        NVARCHAR(255)
                           , [DesignItemName]     NVARCHAR(255)
                           , [DesignNumber]       INT
                           , [RevisionNumber]     INT
                           , [Folio]              INT
                           , [Design Created]     DATETIME
                           , [StatusKey]          INT
                           , [ReportKey]          INT
                           , [ReportSubKey]       INT
                           , [Abbrv]              NVARCHAR(255)
                           , [Archived]           BIT
                           , [ProjGuid]           UNIQUEIDENTIFIER
                           , [RunCount]           INT
                           , [RunUnconCnt]        INT
                           , [ShopsStatus]        INT
                           , [HasAddress]         BIT
                           , [ShopStatusExtended] NVARCHAR(255)
                           , [RegionKey]          INT
                           , [IsLocked]           BIT
                           , [DesignTypeName]     NVARCHAR(255)
                           , [DueDate]            DATETIME
                           , [IsDeleted]          BIT 
            )
            INSERT INTO @DList
                 SELECT
                       [p].[ProjectKey]
                     , [p].[Name] AS [Project Name]
                     , [p].[LegacyKey] AS [Project Number]
                     , [g].[Label] AS [Design Status]
                     , CASE [g].[Label]
                          WHEN ''Dead''
                          THEN 1
                          ELSE 0
                       END AS [Design Locked]
                     , [pd].[DesignKey]
                     , [d].[Name] AS [Design Name]
                     , CONCAT([DE].[Abbreviation] , '' '' , [D].[DesignNumber] ,
                                                CASE
                                                   WHEN [D].[RevisionNumber] IS NULL
                                                   THEN ''''
                                                   ELSE CONCAT('' Rev '' , [D].[RevisionNumber])
                                                END) AS [DesignItemName]
                     , [d].[DesignNumber]
                     , [d].[RevisionNumber]
                     , [d].[Folio]
                     , [d].[tsCreated] AS [Design Created]
                     , [g].[GeneralKey] AS [StatusKey]
                     , [p].[ReportKey]
                     , [p].[ReportSubKey]
                     , [re].[Abbrv]
                     , [p].[Archived]
                     , [p].[ProjectGuid]
                     , (SELECT
                             COUNT([RunKey])
                             FROM [Run]
                             WHERE [DesignKey] = [d].[DesignKey]) AS [RunCnt]
                     , (SELECT
                             COUNT([RunGUID])
                             FROM [RunsUnconsolidated]
                             WHERE [DesignKey] = [d].[DesignKey]) AS [RunUnconCnt]
                     , [d].[ShopsStatus]
                     , CASE
                          WHEN([a].[AddressLine1] = ''Not available''
                              OR [a].[PostalCode] = ''00000'')
                          THEN 0
                          ELSE 1
                       END AS [HasAddress]
                     , [h].[Extended] AS [ShopStatusExtended]
                     , [a].[RegionKey]
                     , [d].[IsLocked]
                     , [DE].[Name]
                     , [P].[BidDueDate] AS [DueDate]
                     , [D].[IsDeleted] AS [IsDeleted]
                       FROM [Project] AS [p]
                           LEFT JOIN [ProjectDesign] AS [pd] ON [p].[ProjectKey] = [pd].[ProjectKey]
                           LEFT JOIN [Design] AS [d] ON [pd].[DesignKey] = [d].[DesignKey]
                           INNER JOIN [DesignType] AS [DE] ON [D].[DesignTypeGuid] = [DE].[DesignTypeGuid]
                           LEFT JOIN [General] AS [g] ON [g].[GeneralKey] = [d].[StatusKey]
                           LEFT JOIN [General] AS [h] ON [h].[GeneralKey] = [d].[ShopsStatus]
                           INNER JOIN [Address] AS [a] ON [a].[AddressGuid] = [p].[ProjectGuid]
                           INNER JOIN [Region] AS [re] ON [a].[RegionKey] = [re].[RegionKey]
                           INNER JOIN '+@SearchKeys+' AS [SK] ON [D].[DesignKey] = [SK].[DesignKey]


 WHERE
                       ((@ProjName = ''%'')
                            OR ([p].[Name] LIKE(''%''+@ProjName +''%''))
                            OR ([p].[LegacyKey] LIKE(@ProjNum)
                               AND [p].[LegacyKey] LIKE(''%''+@ProjName+''%'')))
                           AND [re].[Abbrv] LIKE(@RegAbbrv)
                           AND ([p].[LegacyKey] = ''%''
                               OR [p].[Legacykey] LIKE(@ProjNum))
                           AND [a].[PostalCode] LIKE(@PostalCode)
                           AND [a].[City] LIKE(@City)
                           AND [a].[AddressLine1] LIKE(@AddressLine)
                           AND (@Status = ''%''
                               OR ([D].[IsLocked] = 0
                                  AND [g].[Label] LIKE(@Status)))
                           AND (@IncludeArchived = 1
                               OR [Archived] = 0)
                             AND (@IncludeVoided = 1
                               OR [D].[IsDeleted] = 0)
                           AND (@Folio = ''%''
                             OR [D].[Folio] LIKE(@Folio))
                           AND ([DE].[Abbreviation] = ''%''
                               OR [DE].[Abbreviation] LIKE(@DesignType))
   ';
            DECLARE @Select NVARCHAR(MAX) = ' SELECT
                    *
                    FROM @DList
               ORDER BY
                    '+@CurrentSortBy+'
                    , [Design Name]
                    , [DesignTypeName]
                    , [DesignNumber]
                    , [RevisionNumber]
                            ';
            DECLARE @Query NVARCHAR(MAX) = @Sql + @Select
            EXEC [sp_executesql]
                @Query ,
                @Params ,
                @LastName ,
                @ProjName ,
                @RegAbbrv ,
                @ProjNum ,
                @PostalCode ,
                @City ,
                @AddressLine ,
                @SortBy ,
                @IncludeArchived ,
                @IncludeVoided ,
                @Status ,
                @JobNote ,
                @Folio ,
                @DesignType ,
                @Contact ,
                @Customer
3
  • I'm not certain what you are trying to do or what your complete code looks like, but if you have a populated table variable then dynamic SQL appears to be unnecessary here. Can you please post your entire code base? In the second code snippet, @SearchKeys is definitely not declared.
    – Nick.Mc
    Oct 16, 2018 at 23:03
  • I post my entire code @Nick.McDermaid
    – Juan Pedro
    Oct 16, 2018 at 23:06
  • 1
    I cant see why you are building a dynamic query for this, and not just using an embedded sub query or even better doing it as a CTE? I cant see any reason for going through all the complication for what could be a single query.
    – TomC
    Oct 17, 2018 at 0:16

1 Answer 1

1

Table variables are not inherited in the exec. However, temporary tables are. So I would recommend:

CREATE TABLE #SearchKeys (
    DesignKey INT
);

 . . . 

DECLARE @Sql NVARCHAR(MAX) = '
DECLARE @DList TABLE (
    [ProjectKey] INT,
    [Project Name] NVARCHAR(255)
    ...
   );
INSERT INTO @DList ( . . . )
    SELECT [p].[ProjectKey], [p].[Name] AS [Project Name], ....
    FROM [Project] [p] JOIN
         #SearchKeys [SK]
         ON [D].[DesignKey] = [SK].[DesignKey]
'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.