我正在尝试将stf.PrimarySchoolID
(整数)添加到此现有查询中。我有一个bat文件,它将使用此SQL语句导出CSV。但是,当我打开导出的CSV时,我收到此错误:
Msg 245, Level 16, State 1, Server [SERVER NAME], Line 13
Conversion failed when converting the varchar value ',"' to data type int.
注意:stf.StaffNumber
不是整数,而是字母数字。
SET NOCOUNT ON;
SELECT '"'+
stf.StaffNumber +'","'+
stf.LastName +'","'+
stf.FirstName +'","' +
COALESCE(u.username, '')+'","'+
COALESCE(sfc.[NAME],'') +'",'+
stf.PrimarySchoolID
FROM dbo.UDF_GetCurrentAcademicSessions() cur
JOIN dbo.Course c ON c.AcadSessionID = cur.AcadSessionId
JOIN dbo.Staff stf ON stf.StaffID = c.PrimaryTeacherID
JOIN dbo.StaffClassification sfc ON sfc.StaffClassificationID = stf.PrimaryClassificationID
LEFT OUTER JOIN dbo.[User] u ON u.UserID = stf.UserID
你发现我的错误吗?我对SQL语句不是很有经验,所以感谢任何帮助。
答案 0 :(得分:1)
尝试将stf.StaffNumber
转换为VARCHAR,然后再附加到其中:
CAST(stf.StaffNumber AS VARCHAR)
这同样适用于您将字符串追加到的任何数值。
修改强>
我相信这应该涵盖所有内容:
SELECT '"'+
CAST(stf.StaffNumber AS VARCHAR) +'",'+
CAST(stf.PrimarySchoolID AS VARCHAR) +',"'+
stf.LastName +'","'+
stf.FirstName +'","' +
ISNULL(u.username, '')+'","'+
ISNULL(sfc.[NAME],'') +'",'+
CAST(stf.PrimarySchoolID AS VARCHAR)
另外,在只有一个条件的情况下,您应该使用ISNULL
。 COALESCE
可以正常工作,但它适用于多种条件,即COALESCE(Col1, Col2, Col3, Col4)
答案 1 :(得分:1)
将SELECT
的最后一行更改为:
CAST(stf.PrimarySchoolID as varchar)
答案 2 :(得分:1)
您希望将stf.PrimarySchoolID
转换为字符类型。
...
CAST(stf.PrimarySchoolID AS VARCHAR(20)) -- You can fix length as needed
...
答案 3 :(得分:1)
在连接中使用之前,您需要将stf.PrimarySchoolID
强制转换为字符类型(例如varchar):
SET NOCOUNT ON;
SELECT '"'+
stf.StaffNumber +'",'+
convert(varchar, stf.PrimarySchoolID) +',"'+
stf.LastName +'","'+
stf.FirstName +'","' +
COALESCE(u.username, '')+'","'+
COALESCE(sfc.[NAME],'') +'",'+
stf.PrimarySchoolID
FROM dbo.UDF_GetCurrentAcademicSessions() cur
JOIN dbo.Course c ON c.AcadSessionID = cur.AcadSessionId
JOIN dbo.Staff stf ON stf.StaffID = c.PrimaryTeacherID
JOIN dbo.StaffClassification sfc ON sfc.StaffClassificationID = stf.PrimaryClassificationID
LEFT OUTER JOIN dbo.[User] u ON u.UserID = stf.UserID
您可以使用SQL Server's CONVERT
or SQL ANSI's CAST
进行输入。
答案 4 :(得分:-1)
由于stf.PrimarySchoolID是一个int,并且您尝试将其连接到varchar()字段,因此您收到此错误。试试下面的内容:
SELECT '"'+
stf.StaffNumber +'",'+
cast(stf.PrimarySchoolID as varchar(10)) +',"'+
stf.LastName +'","'+
stf.FirstName +'","' +
COALESCE(u.username, '')+'","'+
COALESCE(sfc.[NAME],'') +'",'+
stf.PrimarySchoolID
答案 5 :(得分:-1)
连接表列可能不匹配或连接给定列。仔细检查哪些列,逻辑被加入。