当前位置: 代码迷 >> Sql Server >> 关于sqlserver语法的有关问题
  详细解决方案

关于sqlserver语法的有关问题

热度:21   发布时间:2016-04-27 10:42:29.0
关于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
------解决方案--------------------
[email protected] 变量可能没有定义成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 [email protected]+'''group by Source ) as A join WFKnowledgeServer_G .dbo .dbo_magzine AS bON a.Source = b.qikan_id 'PRINT @sql
------解决方案--------------------
如果你是SP_EXECUTESQL调用的话,[email protected](max)
  相关解决方案