如何在加入存储过程运行时动态更改表名

时间:2017-04-11 07:50:11

标签: sql-server stored-procedures dynamic

我想创建一个sql存储过程并将其用作crystal report的数据源。我做了如下,它可以正常工作。

CREATE PROCEDURE [dbo].[sp_ScanPointPrint]


 @branch varchar(50),
 @tripID int,
 @scanPoint varchar(50)

AS
BEGIN

    SET NOCOUNT ON;
select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,'dd MMMM, yyyy hh:mm tt'), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName 
from ScanPointLog as sp
left join TableScanPoint1 as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId 
left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
where sp.BranchCode=@branch and sp.ScanPoint=@scanPoint and spt.IsItem=1 and sp.TripId=@tripID

END

GO

我想要执行的操作,我无法做的是将TableScanPoint1表名更改为另一个表名。 TableScanPoint1到TableScanePont8有8个表,结构相同但数据不同。这样做的目的是使一个报表设计使用它作为最终用户想要的。最终用户将在运行时从vb.net应用程序中选择table,branch,tripid和scanpoint。

任何人都可以帮我这个吗? 感谢

2 个答案:

答案 0 :(得分:1)

CREATE PROCEDURE [dbo].[sp_ScanPointPrint]


 @branch varchar(50),
 @tripID int,
 @scanPoint varchar(50),
 @tablenametoscan varchar(200)

AS
BEGIN

    SET NOCOUNT ON;

declare @sqltoexecute varchar(max)
set @sqltoexecute = '
select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,'dd MMMM, yyyy hh:mm tt'), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName 
from ScanPointLog as sp
left join ' +  @tablenametoscan + ' as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId 
left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
where sp.BranchCode=@branch and sp.ScanPoint=@scanPoint and spt.IsItem=1 and sp.TripId=@tripID '


exec sp_executesql @sqltoexecute 
END

GO

答案 1 :(得分:0)

请尝试使用以下查询:

    CREATE PROCEDURE [dbo].[sp_ScanPointPrint]

     @branch VARCHAR(50),
     @tripID INT,
     @scanPoint VARCHAR(50),
     @table VARCHAR(100)

    AS
    BEGIN
    SET NOCOUNT ON;

    DECLARE @query NVARCHAR(max)
    SET @query = '
    select sp.BranchCode, sp.ScanPoint, sp.TripId, sp.DoneBy,FORMAT(sp.DateTime,''dd MMMM, yyyy hh:mm tt''), sp.Driver, sp.CarNo, sp.ItemShouldBe, sp.ActualTaken, sp.MissedAny, sp.MissedCount, sp.TookExtra, sp.ExtraCount, spT.OrderNo,spt.ItemBarcode, oi.ItemName 
    from ScanPointLog as sp
    left join ' +  @table + ' as spT on sp.BranchCode = spT.BranchCode and sp.TripId = spT.TripId 
    left join OrderItem as Oi on spt.OrderNo=oi.OrderNO and spt.ItemBarcode=oi.ItemBarcode
    where sp.BranchCode=@branch and sp.ScanPoint=@scanPoint and spt.IsItem=1 and sp.TripId=@tripID '


    EXEC (@query) 
    END

    GO