我试图创建一个动态SQL查询,但不幸的是它显示错误:
Msg 245,Level 16,State 1,Line 14
从SimulationVisit SV内部联接学生转换varchar值'select count(s.ID),count(distinct(s.ID))时转换失败。 ID = SV。 AC上的学生ID内部联接活动上下文AC。 ID = SV。 ActivityContextID WHERE(AC.TenantID ='to data type int。
我的代码
declare @DateRangeStart [DATETIME2](7),
@DateRangeEnd [DATETIME2](7),
@TenantID [SMALLINT] ,
@ActivityContextID [INT],
@StudentID [INT] = NULL
'select count(s.ID),count(distinct(s.ID))
from SimulationVisit SV
inner join Student s on s.ID = SV.StudentID
inner join ActivityContext AC on AC.ID = SV.ActivityContextID
where (AC.TenantID = ' + @TenantID + ' OR @TenantID is null)
and (AC.ID =' + @ActivityContextID + ')
and (SV.StudentID = ' + @StudentID + ')';
请帮我解决这个问题
答案 0 :(得分:1)
不要创建串联字符串的查询,这是一种不好的做法。只写:
var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
jsonOutputFormatter.WriteObject(stringWriter, value);
var responseBody = stringWriter.ToString();
答案 1 :(得分:1)
如果动态sql是必需的,请使用参数化动态sql查询:
EXEC sp_executesql N'
SELECT COUNT(s.ID),COUNT(distinct(s.ID))
FROM SimulationVisit SV
INNER JOIN Student S ON s.ID=SV.StudentID
INNER JOIN ActivityContext AC ON AC.ID=SV.ActivityContextID
WHERE (AC.TenantID = @TenantID OR @TenantID is null)
AND (AC.ID = @ActivityContextID)
AND (SV.StudentID = @StudentID)',
N' @TenantID [SMALLINT] ,
@ActivityContextID [INT],
@StudentID [INT]',
@TenantID, @ActivityContextID, @StudentID
答案 2 :(得分:0)
转换INT& BIGINT值为VARCHAR数据类型,格式如下:
'SELECT count(s.ID),count(distinct(s.ID))
FROM SimulationVisit SV
INNER JOIN Student s on s.ID = SV.StudentID
INNER JOIN ActivityContext AC on AC.ID = SV.ActivityContextID
WHERE (AC.TenantID = '+ CAST( @TenantID AS VARCHAR ) + ' OR
@TenantID is null) AND
(AC.ID =' + CAST ( @ActivityContextID AS VARCHAR ) + ')
AND (SV.StudentID = '+ CAST( @StudentID AS VARCHAR ) +')'
答案 3 :(得分:0)
更新您的查询,如下所示,您必须将变量转换为字符串/ varchar值以执行动态查询
message
答案 4 :(得分:0)
由于这是动态sql,最终的sql语句需要是varchar。相应地转换输入参数
'select count(s.ID),count(distinct(s.ID)) from SimulationVisit SV inner join Student s on s.ID=SV.StudentID
inner join ActivityContext AC on AC.ID=SV.ActivityContextID
WHERE (AC.TenantID = '+Cast(@TenantID as varchar(50))+' OR '+Cast(@TenantID as varchar(50))+' is null)
AND (AC.ID =' +Cast(@ActivityContextID as varchar(50))+')
AND (SV.StudentID = '+Cast(@StudentID as varchar(50))+')'