寻找一种用声明变量替换查询中表名的方法

时间:2019-06-11 15:45:25

标签: sql sql-server

想知道是否有可能通过为下面的查询在头部声明一个变量来替换表名 DCI_ARD

尝试了多种方法,但是我遇到的问题是我在同一查询中有多个',并且中断了声明。

即。 CONCAT('(',M.ManufacturerID,')',

即。 STRING_AGG(CategoryID,',')作为CategoryID

SELECT * FROM (

    SELECT [id]
          ,[brandaaiaid]
          ,M.ManufacturerID
          ,CONCAT('(',M.ManufacturerID,')',exppartno) AS TempManufacturerSKU
          ,[company]
          ,[fromyear]
          ,[toyear]
          ,[makename]
          ,[modelname]
          ,[submodelname]
          ,[engbase]
          ,[partterminologyname]
          ,[position]
          ,[exppartno]
          ,[mfrlabel]
      FROM DCI_ARD AS DS
      LEFT JOIN [dbo].[Manufacturer] AS M ON DS.brandaaiaid = M.AAIAID

      ) AS T

      LEFT JOIN [dbo].[ProductVariant] AS PV ON T.TempManufacturerSKU = PV.ManufacturerPartNumber
      LEFT JOIN 
      (select ProductId, STRING_AGG(CategoryID, ',') as CategoryID
    from productCategory
    GROUP BY ProductId) as PC ON PV.ProductID = PC.ProductID ORDER BY id ASC

1 个答案:

答案 0 :(得分:0)

  

尝试了多种方法,但是我遇到的问题是我在同一查询中有多个',并且中断了声明。

基于此,我假设您正在尝试构建字符串并使用sp_executesql,在这种情况下,SQL中出现的任何单引号都需要通过加倍来进行转义。例如,如果您要运行此命令:

<section class="container">
  <div class="item" id="main-column">
    <button onclick="pushInput()">+</button>
    <input/>
  </div>
  <div class="item">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </div>
</section>

使用sp_executesql:

SELECT CONCAT('(','Test',')') FROM MyTable