如何将动态SQL查询转换为静态查询

时间:2016-02-04 06:25:33

标签: sql sql-server-2008-r2

我在SQL Server中有以下动态脚本

DECLARE @ArchiveDbName NVARCHAR(100)
SELECT TOP 1 @ArchiveDbName = ls.ArchiveDbName
FROM   LocalSetting ls

DECLARE @Query NVARCHAR(MAX) =
        'SELECT BusinessDocTypeID,
       RegDate,
       PersonID,
       ProductCode,
       bddv.Group4Code,
       NominalCode,
       UnitID,
       UnitName,
       ProductDescription,
       GrossWeight,
       NetWeight,
       Qty,
       SalePrice,
       UnitPrice,
       TotalNetWeight,
       TotalGrossWeight,
       TotalPrice,
       w.WHCode,
       @FinancialYear
FROM   ' + @ArchiveDbName +
        '.dbo.udfv_BusinessDocDetailView(@RunDate) AS bddv
       INNER JOIN dbo.udft_BusinessDoc(@RunDate) bd
            ON  bd.BusinessDocNo = bddv.BusinessDocNo
       INNER JOIN dbo.udft_WHDoc(@RunDate) w
            ON  w.WHDocNo = bd.WHDocNo
       WHERE  (bd.BusinessDocTypeID = @BusinessDocTypeID)
              AND bd.RegDate BETWEEN @FromShamsiDate AND @ToShamsiDate'

我希望得到静态的形式。是否有任何方法可以进行此转换?

其实我想在表值函数中使用动态查询。但是SQL Server并没有让我做出这样的选择。

1 个答案:

答案 0 :(得分:0)

使用仅SQL解决方案是不可能的。它必须是动态的。一种替代解决方案是在.NET中构造查询并执行然后通过ADO.net执行它。它实际上与动态SQL相同(但技术上不是)