Search code examples
sqlsql-servertemp-tables

Why can't create the #Articole table


I try to create one tenp table (#Articole) but without succes. Where is the mistake?

Declare @Articol int,
       @Sql NVarchar(max)
set @Articol = 99190
set @Sql=N'
select im.ItemName, im.ItemCode, d.ItemId as PromoId, im.Enabled, im.ItemId, dfv.DiscountFilterValueId
into #Articol
from Discount d (nolock) 
join DiscountFilter df (nolock) on df.DiscountId = d.ItemId
Join DiscountFilterValue dfv (nolock) on dfv.DiscountFilterId = df.DiscountFilterId
join Item i (nolock) on d.ItemId = i.ItemId
Join Item im (nolock) on im.ItemId = dfv.TextValue
where df.EntityId = 184'

IF @Articol <> -1 set @Sql = @Sql + ' and im.ItemId = @Articol'
If @Articol = -1 set @Sql = @Sql
exec sp_executesql @Sql, N'@Articol int', @Articol

select * from #Articole

Solution

  • Try this:

        CREATE TABLE #Articole (ItemName NVARCHAR(MAX), ItemCode INT, ItemId INT, Enabled BIT, SecondItemId INT, DiscountFilterValueId INT)
        SET @Sql=N'
        insert into #Articol
        select im.ItemName, im.ItemCode, d.ItemId as PromoId, im.Enabled, im.ItemId, dfv.DiscountFilterValueId      
        from Discount d (nolock) 
        join DiscountFilter df (nolock) on df.DiscountId = d.ItemId
        Join DiscountFilterValue dfv (nolock) on dfv.DiscountFilterId = df.DiscountFilterId
        join Item i (nolock) on d.ItemId = i.ItemId
        Join Item im (nolock) on im.ItemId = dfv.TextValue
        where df.EntityId = 184'
    
        IF @Articol <> -1 set @Sql = @Sql + ' and im.ItemId = @Articol'
        If @Articol = -1 set @Sql = @Sql
        exec sp_executesql @Sql, N'@Articol int', @Articol
    
        select * from #Articole
    

    I didn't know your columns type, I just guess it. Make sure types are proper