我尝试创建一个Tenp表(#Articole),但是没有成功。错误在哪里?
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
答案 0 :(得分:1)
尝试一下:
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
我不知道您的栏类型,我只是猜到了。确保类型正确
答案 1 :(得分:0)
编辑,您根本不需要动态SQL。这足以满足您的原始查询:and (@articol = -1 or im.ItemId = @articol)
。
临时表仅限于创建它的范围。您要么需要在sp_executesql
之前创建它,要么将其余语句移动到动态查询字符串本身中,或者通过以##
为前缀而不是单个#
作为全局临时表
由于我在实际查询中不了解表的架构,因此以下是预先创建表的技巧。
select top 0 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
@Sql NVarchar(max)
set @Articol = 99190
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
答案 2 :(得分:0)
我们可以在两个范围内创建临时表,
#Articole
##Articole
来创建要么在本地范围之外创建临时表,要么在全局范围内创建它。