我正在尝试创建一个漂亮的列来显示,但我无法使用空格或连字符。我希望列显示为
2014年6月或2014年6月但由于查询已经在字符串中,我尝试以正常方式插入时出现错误。
以下是我遇到问题的部分:
(LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime))) as leadmonth
以下是上下文查询的其余部分:
set @query = 'SELECT name AS "Lead Source",' + @cols + '
from
(
SELECT d.name, COUNT(u.lead_source_id) AS totalLeads, + "["+ (LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime)))+"] as leadmonth" +
FROM DI_TrackingDB.dbo.userleads u
INNER JOIN GSPremiumServices.dbo.supplier_product_lead_source_def d ON d.lead_source_id = u.lead_source_id
WHERE vend_id = 355135
AND u.lead_source_id IS NOT NULL
GROUP BY u.lead_source_id, d.name, DATENAME(month, leadtime), DATEPART(year, leadtime), Convert(varchar(7), leadtime, 126)
) x
pivot
(
max(totalLeads)
for leadmonth in (' + @cols + ')
) p '
请记住我正在设置@query
所以我已经在一个字符串里面了。
任何建议都表示赞赏。
答案 0 :(得分:1)
答案很简单。不确定人们是否不太了解我的初始问题,但答案是在内部字符串的两侧使用两个'
。以下是有效代码的最终版本。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(monthyear)
FROM (SELECT DISTINCT (LEFT(DATENAME(MONTH, month_start),3)+ '-' + CONVERT(VARCHAR, DATEPART(YEAR, month_start))) AS monthyear, month_start
FROM dbo.mo_vendor_month WITH(NOLOCK)
WHERE vend_id = #arguments.prospectId#
AND month_start >= '#startDate#'
)alertsMonths
ORDER BY month_start ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT ' + @cols + '
FROM
(
SELECT total_unique_leads,(LEFT(DATENAME(MONTH, month_start),3)+ ''-'' + CONVERT(VARCHAR, DATEPART(YEAR, month_start))) AS monthyear
FROM dbo.mo_vendor_month
WHERE vend_id = #arguments.prospectId#
AND month_start >= ''#startDate#''
GROUP BY month_start, total_unique_leads
) x
pivot
(
max(total_unique_leads)
FOR monthyear IN (' + @cols + ')
) p '
EXECUTE(@query)
答案 1 :(得分:0)
只需在您正在构建的字段名称周围放置方括号,如下所示:
"[" + (LEFT(DATENAME(month, leadtime),3) + " " + CONVERT(varchar, DATEPART(year, leadtime))) + "] as leadmonth"
我还准备好处理可能出现的任何单引号或双引号(通过在构建字符串时根据需要转义它们)。除此之外,将字段名称括在方括号中允许您使用通常在标识符名称中不允许的字符。