日期:2014-05-17  浏览次数:20608 次

关于sqlserver语法的问题
select B.ISSN,b.qikan_id , B.中文刊名,B.主管部门,B.主办单位,a.下载次数 from (
select Source ,COUNT(Source ) as 下载次数 from WFKS_LogItem 
where [Resource]= 'PeriodicalIssue'
and OccurDate between '2012-9-1' and '2012-10-1'
and GroupId ='hkzwdx2'
group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS b
ON a.Source = b.qikan_id 


以上这个sql 执行没有问题

我如何把以上这个sql 写到 变量里使用

set @sql = 'select B.ISSN,b.qikan_id , B.中文刊名,B.主管部门,B.主办单位,a.下载次数 from (
select Source ,COUNT(Source ) as 下载次数 from WFKS_LogItem 
where [Resource]= ''PeriodicalIssue''
and OccurDate between ''2012-9-1'' and ''2012-10-1''
and GroupId =''hkzwdx2''
group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS b
ON a.Source = b.qikan_id '

总提示我语法不对

------解决方案--------------------
SQL code
DECLARE @sql NVARCHAR(max)
 SET @sql = 'select B.ISSN,b.qikan_id , B.中文刊名,B.主管部门,B.主办单位,a.下载次数 from (
 select Source ,COUNT(Source ) as 下载次数 from WFKS_LogItem  
 where [Resource]= ''PeriodicalIssue''
 and OccurDate between ''2012-9-1'' and ''2012-10-1''
 and GroupId =''hkzwdx2''
 group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS b
 ON a.Source = b.qikan_id '
 PRINT @sql

------解决方案--------------------
--try
DECLARE @sql NVARCHAR(max)
 SET @sql = 'select B.ISSN,b.qikan_id , B.中文刊名,B.主管部门,B.主办单位,a.下载次数 from (
 select Source ,COUNT(Source ) as 下载次数 from WFKS_LogItem
 where [Resource]= '+'''PeriodicalIssue'''+'
 and OccurDate between '+'''2012-9-1'''+' and '+'''2012-10-1'''+'
 and GroupId ='+'''hkzwdx2'''+'
 group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS b
 ON a.Source = b.qikan_id '
 PRINT @sql
------解决方案--------------------
楼主定义的@sql 变量可能没有定义成nvarchar,或者长度不够。定义的内容没有什么问题。
------解决方案--------------------
varchar长度问题
------解决方案--------------------
比如要吧GroupId用变量代替,那么就按照下面的写
注意引号数量
SQL code

DECLARE @sql VARCHAR(MAX),@GroupId VARCHAR(10)
SET @GroupId='hkzwdx2'
set @sql = 'select B.ISSN,b.qikan_id , B.中文刊名,B.主管部门,B.主办单位,a.下载次数 from (
select Source ,COUNT(Source ) as 下载次数 from WFKS_LogItem  
where [Resource]= ''PeriodicalIssue''
and OccurDate between ''2012-9-1'' and ''2012-10-1''
and GroupId ='''+@GroupId+'''
group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS b
ON a.Source = b.qikan_id '
PRINT @sql

------解决方案--------------------
如果你是SP_EXECUTESQL调用的话,定义@sql的时候类型是否为nvarchar(max)