我使用数据透视表但是当我执行时我得到了这个错误请帮助我我坚持这个感谢提前抱歉如果有任何错误请同时告诉我如何在sql server中处理字符串中的字符串我使用“'' '','' - '''但不确定它是否正确请尽快帮助我查询
SELECT @SQL = 'SELECT '
WHile @I <= @Months
BEGIN
SET @YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, @I, @StartDate), 13), 3,9)), ' ', '-')
SET @ColumnText = @YearMonth
SET @SQL = @SQL + 'ISNULL([' + @YearMonth + '], 0.00) as ''' + @ColumnText + ''','
SET @I = @I +1
END
Set @I = 0
SET @SQL = @SQL + 'Product,Supplier,PackPrice,QuantityInPack,Code,SupplierID,Description,RebateAmount
FROM
(
SELECT p.NAME AS product,p.Code AS Code,P.Description as Description,oi.PackPrice,oi.QuantityInPack AS Packsize,S.ID AS SupplierID,s.[Name] AS Supplier,
CASE when oi.RebateType=2 then (oi.PackPrice*oi.RebateAmount)/100 ELSE oi.RebateAmount END AS RebateAmount ,o.Total as TotalSale,
REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, O.CreatedDate, 13), 3,9)), '' '',''-'') as tdate
FROM dbo.SCM_Product p WITH (NOLOCK)
INNER JOIN SCM_OrderItem oi WITH (NOLOCK) ON oi.ProductId = p.ID
LEFT OUTER JOIN dbo.SCM_Supplier s WITH(NoLock) ON oi.SupplierID=s.ID
LEFT OUTER JOIN SCM_Order o WITH (NOLOCK) ON o.Id = oi.ProductId AND O.Status <> 5 -- CANCELLED
AND O.Deleted = 0
WHERE ('''+@SupplierID+''' IS NULL OR s.ID IN (SELECT * FROM GetIDsTableFromIDsList(@SupplierID)))
AND ('''+@ProductID+''' IS NULL OR p.ID IN (SELECT * FROM GetIDsTableFromIDsList(@ProductID)) )
AND (o.CreatedDate >= '''+ dbo.GetDatePart(@StartDate) +''' AND o.CreatedDate <= '''+ dbo.GetDatePart(@Enddate) +''')
GROUP BY REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, o.CreatedDate, 13), 3,9)), '' '',''-''),
s.ID,p.Code,p.NAME,s.NAME,P.Description,oi.packPrice,oi.QuantityInPack,oi.RebateAmount,oi.RebateType,oi.PackPrice,o.Total
) SD
PIVOT
( SUM( SD.TotalSale) FOR SD.tdate IN ('
WHile @I <= @Months
BEGIN
SET @YearMonth = REPLACE(LTRIM(SUBSTRING(CONVERT(VARCHAR, DateAdd(Month, @I, @StartDate), 13), 3,9)), ' ', '-')
IF @I = @Months
BEGIN
SET @SQL = @SQL + ' [' + @YearMonth + ']'
END
ELSE
BEGIN
SET @SQL = @SQL + ' [' + @YearMonth + '],'
END
SET @I = @I +1
END
SET @SQL = @SQL + ')) as pvt
ORDER BY Supplier '
--EXEC(@SQL)
PRINT @SQL
答案 0 :(得分:0)
最简单的方法是使用QUOTENAME()
函数,因为在大型查询中很容易错过引用。
例如:
DECLARE @name AS CHAR(10) = 'Revolver'
DECLARE @sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='+ QUOTENAME(@name,'''')
PRINT @sql;
或
DECLARE @name AS CHAR(10) = 'Revolver'
DECLARE @sql as NVARCHAR(300) = 'SELECT *
FROM Music.Album
WHERE Name ='''+ @name + ''''
PRINT @sql;