求助:SqlDataAdapter填充DataSet时#字符丢失并拼接值(如10#1000变101000)
问题:SqlDataAdapter填充DataSet时丢失#字符并拼接数值
在C#应用中调用存储过程获取数据,SQL查询在SQL Server直接执行时返回正确值,但通过SqlDataAdapter填充DataSet时,原本类似10#1000的值变成了101000,#字符被移除且数值被拼接。
数据库表中的原始数据如下:
| CancelChargesStep1 | CancelChargesStep2 | CancelChargesStep3 |
|---|---|---|
| 10#1000 | 20#500 | 30#250 |
C#简化代码:
SqlCommand sqlComm = new SqlCommand("MyStoredProcedure", sqlConn); sqlComm.CommandType = CommandType.StoredProcedure; SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = sqlComm; DataSet ds = new DataSet(); da.Fill(ds);
已尝试在SQL查询中将列转换为VARCHAR或NVARCHAR,确保值被视为字符串:
SELECT CAST(CancelChargesStep1 AS VARCHAR(50)) AS CancelChargesStep1 FROM MyTable;
解决方法
- 排查存储过程的类型处理:确保存储过程中没有对目标列做隐式数值转换,不要在CAST之前将列作为数值参与运算,直接对原始列做字符串转换,例如改用
CONVERT(NVARCHAR(50), CancelChargesStep1)明确指定类型。 - 手动指定DataTable列类型:在填充前先创建DataTable并指定列的字符串类型,避免SqlDataAdapter自动推断错误类型:
DataTable dt = new DataTable(); dt.Columns.Add("CancelChargesStep1", typeof(string)); dt.Columns.Add("CancelChargesStep2", typeof(string)); dt.Columns.Add("CancelChargesStep3", typeof(string)); da.Fill(dt); - 检查存储过程返回的元数据:如果存储过程通过临时表或动态SQL返回数据,可能导致SQL Server返回错误的列类型元数据。可以在存储过程中显式定义临时表的字符串列类型后再插入数据,确保返回的列类型为字符串。
- 验证DataSet列类型:填充后检查
ds.Tables[0].Columns["CancelChargesStep1"].DataType,确认是否为System.String,如果是数值类型,说明自动推断错误,需要手动指定类型。
内容的提问来源于stack exchange,提问作者kanchan
相关产品推荐
相关产品推荐

