Alter procedure spMRI_TAG_try
@DocNum int
as
declare @cnt int
declare @count int
declare @cardname nvarchar(100)
declare @Docdate datetime
declare @itemCode nvarchar(50)
declare @Dscription nvarchar(100)
declare @Quantity numeric(19,6)
declare @ManBtchNum char(1)
declare @SalPackUn numeric(19,6)
declare @ExpDate datetime
begin
set @cnt = 1
select @Count = pdn1.Quantity/OITM.SalPackUn from pdn1 inner join OITM on pdn1.ItemCode=OITM.ItemCode
while @cnt <= @count
insert into #temp2 values(@cardname,@DocDate,@itemcode,@Dscription,@Quantity,@ManBtchNum,@SalPackUn,@ExpDate)
select @cardname = a.CardName,@DocDate=a.DocDate,@itemcode=b.ItemCode,@Dscription=b.Dscription,@Quantity=b.Quantity,@ManBtchNum=c.ManBtchNum,@SalPackUn=c.SalPackUn,@ExpDate=d.ExpDate
from OPDN a inner join PDN1 b on a.DocEntry = b.DocEntry inner join OITM c on c.ItemCode = b.ItemCode inner join OBTN d on c.ItemCode = d.ItemCode and a.DocNum=@DocNum and d.ExpDate is not null
set @cnt=@cnt+1
end
select * from #temp2
但是给了我一个invalid object name #temp2
错误。
答案 0 :(得分:0)
在while循环之前创建临时表:
create table #temp2 (Cardname ...)
while @cnt <= @count
insert into #temp2 values(@cardname,@DocDate,@itemcode,@Dscription,@Quantity,@ManBtchNum,@SalPackUn,@ExpDate)
select @cardname = a.CardName,@DocDate=a.DocDate,@itemcode=b.ItemCode,@Dscription=b.Dscription,@Quantity=b.Quantity,@ManBtchNum=c.ManBtchNum,@SalPackUn=c.SalPackUn,@ExpDate=d.ExpDate
这里有两点:
答案 1 :(得分:0)
说实话,你的SP是一个搞乱的代码:)
我建议你像这样重写:
ALTER PROCEDURE spMRI_TAG_try
@DocNum int
AS
--Drop table if it exists
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
--create table
CREATE TABLE #temp2 (
cardname nvarchar(100),
Docdate datetime,
itemCode nvarchar(50),
Dscription nvarchar(100),
Quantity numeric(19,6),
ManBtchNum char(1),
SalPackUn numeric(19,6),
ExpDate datetime
)
--Make the insertion
INSERT INTO #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=@DocNum and d.ExpDate is not null
--output
SELECT *
FROM #temp2
不需要while循环(我甚至无法理解你将如何切换行,在你的解决方案中它将在'@count'时间内写入相同的行),你可以直接在临时表中写入所有数据。 / p>
由于在您尝试插入时没有#temp2
表,您会收到错误,也不会检查该表是否已存在。
正如Kannan Kandasamy在回答中指出的那样,另一种方法是使用SELECT * INTO #temp2
,它可以通过这种方式实现:
ALTER PROCEDURE spMRI_TAG_try
@DocNum int
AS
IF OBJECT_ID(N'#temp2') IS NOT NULL DROP TABLE #temp2
SELECT a.CardName,
a.DocDate,
b.ItemCode,
b.Dscription,
b.Quantity,
c.ManBtchNum,
c.SalPackUn,
d.ExpDate
INTO #temp2
FROM OPDN a
INNER JOIN PDN1 b
ON a.DocEntry = b.DocEntry
INNER JOIN OITM c
ON c.ItemCode = b.ItemCode
INNER JOIN OBTN d
ON c.ItemCode = d.ItemCode and a.DocNum=@DocNum and d.ExpDate is not null
SELECT *
FROM #temp2