从SQL Server存储过程返回的值未正确转换

如何解决从SQL Server存储过程返回的值未正确转换

我有一条从SQL Server返回的行和一个整数列值,该值在C#中无法正确转换为布尔值。

我想将整数1转换为布尔值true。但这并没有做到。它将1转换为false或认为它为0并转换为false。

blogPublishedByBlogId.LikeDisabled = Convert.ToBoolean(getblogPublishedByBlogIdReader["LikeDisabled"]);

这是存储过程通过SSMS返回的行:

enter image description here

LikeDisabled列是一个整数,值= 1,但是在C#中将其转换为值0。为什么?像这样的简单事情应该起作用。这没有道理。

这是在调用存储过程并将数据取入模型后显示的代码。

我放入两行“测试代码”以查看整数值。它由存储过程以整数值= 1返回,但是在转换函数Convert.ToInt32之后,我得到了0。请参见下文。

enter image description here

这是几行后的完全填充的模型。当LikeDisabled应该为true时,布尔值都为false。

enter image description here

这是存储过程。它从数据库表中获取所需的数据,并根据LikeDisabled(当前为'L')来设置DisLikeDisabled@LikeOrDislikeIndicator = 'L'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetBlogPublishedByBlogId]
    @a_UserName   varchar(250) = NULL,@a_IpAddress  varchar(250) = NULL,@a_BlogId     int = NULL,@a_UserId     int = NULL
AS 
BEGIN
    DECLARE @RowCount                  int,@ReturnCode                int,@CurrentDateTime           datetime,@Count                     int,@UserType                  varchar(25) = '',@LikeOrDislikeIndicator    char(1) = '',-- 'L' for like,'D' for dislike.
            @BlogId                    int = 0,@BlogTitle                 varchar(250) = '',@BlogContent               varchar(max) = '',@LikeCount                 int = 0,@DisLikeCount              int = 0,@ModifiedDateTime          datetime = NULL,@CreatedDateTime           datetime = NULL,@LikeDisabled              int = 0,@DisLikeDisabled           int = 0,@Message                   varchar(max),@ApiMessageOut             varchar(max),@ApiAccessSwitchOut        bit

SELECT @CurrentDateTime = GETDATE()


DECLARE @ErrorLine      AS INT;
DECLARE @ErrorMessage       AS VARCHAR(2048);
DECLARE @ErrorNumber        AS INT; 
DECLARE @ErrorSeverity      AS INT; 
DECLARE @ErrorState     AS INT; 
DECLARE @DatabaseName       AS VARCHAR(255);
DECLARE @ServerName     AS VARCHAR(255);
DECLARE @ErrorDescription   AS VARCHAR(MAX);
DECLARE @CRLF           AS VARCHAR(2);
    
BEGIN TRY

   SET NOCOUNT ON;

   IF ( ( @a_UserName  = '' OR @a_UserName  IS NULL ) OR ( @a_IpAddress = '' OR @a_IpAddress IS NULL ) 
   OR ( @a_BlogId IS NULL ) OR ( @a_UserId IS NULL ) )
      BEGIN
         SELECT @Message = 'Warning - invalid parameters. They cannot be null or empty.'    

         IF ( @a_UserName = '' OR @a_UserName IS NULL )
             BEGIN
                SET @a_UserName = 'No "user name" parameter provided.'
             END

         IF ( @a_IpAddress = '' OR @a_IpAddress IS NULL )
             BEGIN
                SET @a_IpAddress = 'No "ip address" parameter provided.'
             END

        RAISERROR (@Message,16,1)
      END
   ELSE
      BEGIN
           -- Do the API security check. If this user is valid,you can continue with further processing.
           SELECT @ReturnCode = -1
           EXECUTE @ReturnCode = dbo.GetApiAccess
                     @CurrentDateTime,@a_UserName,@a_IpAddress,@a_ApiAccessSwitchFromGet = @ApiAccessSwitchOut OUTPUT,@a_ApiMessageFromGet = @ApiMessageOut OUTPUT

           IF @ReturnCode = -1
                BEGIN 
                   RAISERROR ('Critical Error - procedure GetBlogPublishedByBlogId failed during execute of procedure GetApiAccess',1 )
                END
    
           -- Web api access was granted. 
           IF @ApiAccessSwitchOut = 1
               BEGIN
                   SELECT @BlogId = Blogid,@BlogTitle = BlogTitle,@BlogContent = BlogContent,@LikeCount = LikeCount,@DisLikeCount = DisLikeCount,@ModifiedDateTime = ModifiedDateTime,@CreatedDateTime = CreatedDateTime       
                   FROM dbo.Blog
                   WHERE ( BlogId = @a_BlogId AND ActiveSwitch = 1 )

                   SELECT @ReturnCode = @@ERROR,@RowCount = @@ROWCOUNT

                   IF @ReturnCode <> 0
                       BEGIN 
                          SELECT @Message = 'Critical Error - procedure GetBlogPublishedByBlogId during the 1st select.'
                          RAISERROR (@Message,1)
                       END  

                    IF @RowCount = 0
                        BEGIN 
                               SELECT 2 as Status,0 as Blogid,'' as BlogTitle,'' as BlogContent,0 as LikeCount,0 as DisLikeCount,NULL as ModifiedDateTime,NULL as CreatedDateTime,@LikeDisabled as LikeDisabled,@DisLikeDisabled as DisLikeDisabled
                        END 
                    ELSE
                        BEGIN 
                        SELECT @LikeOrDislikeIndicator = LikeOrDislikeIndicator
                        FROM dbo.[UserBlogPreference]
                        WHERE ( BlogId = @a_BlogId AND UserId = @a_UserId )

                        SELECT @ReturnCode = @@ERROR,@RowCount = @@ROWCOUNT

                            IF @ReturnCode <> 0
                               BEGIN 
                                SELECT @Message = 'Critical Error - procedure GetBlogPublishedByBlogId during the 2nd select.'
                                RAISERROR (@Message,1)
                               END  

                            IF ( @RowCount = 0 )
                                BEGIN
                                    SELECT @LikeDisabled = 0,@DisLikeDisabled = 0                                
                                END
                            ELSE
                                BEGIN
                                IF @LikeOrDislikeIndicator = 'L'
                                   BEGIN
                                    SELECT @LikeDisabled = 1,@DisLikeDisabled = 0 
                                   END
                                ELSE
                                   BEGIN
                                      SELECT @LikeDisabled = 0,@DisLikeDisabled = 1 
                                   END
                                END
                                
                            -- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++      
                            -- Return data. 
                            --+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                                         SELECT 1 as Status,@Blogid as Blogid,@BlogTitle as BlogTitle,@BlogContent as BlogContent,@LikeCount as LikeCount,@DisLikeCount as DisLikeCount,@ModifiedDateTime as ModifiedDateTime,@CreatedDateTime as CreatedDateTime,@DisLikeDisabled as DisLikeDisabled
                        END 
               END
           ELSE
               BEGIN

                  RAISERROR (@ApiMessageOut,1 )
              END
      END
    
   RETURN 0

END TRY

BEGIN CATCH
    ---- code not shown.       
END CATCH
END

这是UserBlogPreference表,该表具有用于确定LikeDisabled和DisLikeDisabled设置的指示器。设置为“ L”。

enter image description here

这是模型类:

using System;
using System.ComponentModel.DataAnnotations;

namespace GbngWebApi2.Models
{
    public class BlogPublishedByBlogId
    {
        public int BlogId { get; set; }        
        public string BlogTitle { get; set; }
        public string BlogContent { get; set; }
        public int LikeCount { get; set; }
        public int DisLikeCount { get; set; }
        public DateTime ModifiedDateTime { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public bool LikeDisabled { get; set; }
        public bool DisLikeDisabled { get; set; }
    }
}

这是对存储过程的调用,是上面的屏幕截图:

public BlogPublishedByBlogIdResults GetBlogPublishedByBlogId(string userName,string ipAddress,int blogId,int userId)
{
    BlogPublishedByBlogIdResults blogPublishedByBlogIdResults = new BlogPublishedByBlogIdResults();

    SqlDataReader getblogPublishedByBlogIdReader = null;

    try
    {
        dbFunc.OpenDB();

        SqlCommand cmd = new SqlCommand("dbo.GetBlogPublishedByBlogId",dbFunc.objConn);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@a_UserName",userName);
        cmd.Parameters.AddWithValue("@a_IpAddress",ipAddress);
        cmd.Parameters.AddWithValue("@a_BlogId",blogId);
        cmd.Parameters.AddWithValue("@a_UserId",userId);

        getblogPublishedByBlogIdReader = cmd.ExecuteReader();

        // There will be only 1 entry.
        while (getblogPublishedByBlogIdReader.Read())
        {
            BlogPublishedByBlogId blogPublishedByBlogId = new BlogPublishedByBlogId();

            blogPublishedByBlogIdResults.Status = Convert.ToInt32(getblogPublishedByBlogIdReader["Status"]);
            blogPublishedByBlogId.BlogId = Convert.ToInt32(getblogPublishedByBlogIdReader["BlogId"]);
            blogPublishedByBlogId.BlogTitle = getblogPublishedByBlogIdReader["BlogTitle"].ToString();
            blogPublishedByBlogId.BlogContent = getblogPublishedByBlogIdReader["BlogContent"].ToString();
            blogPublishedByBlogId.LikeCount = Convert.ToInt32(getblogPublishedByBlogIdReader["LikeCount"]);
            blogPublishedByBlogId.DisLikeCount = Convert.ToInt32(getblogPublishedByBlogIdReader["DisLikeCount"]);
            blogPublishedByBlogId.ModifiedDateTime = Convert.ToDateTime(getblogPublishedByBlogIdReader["ModifiedDateTime"]);
            blogPublishedByBlogId.CreatedDateTime = Convert.ToDateTime(getblogPublishedByBlogIdReader["CreatedDateTime"]);

            // Test code to see what the value is before trying to convert to boolean below.
            int likeDisabled = Convert.ToInt32(getblogPublishedByBlogIdReader["LikeDisabled"]);
            int DislikeDisabled = Convert.ToInt32(getblogPublishedByBlogIdReader["DisLikeDisabled"]);

            blogPublishedByBlogId.LikeDisabled = Convert.ToBoolean(getblogPublishedByBlogIdReader["LikeDisabled"]);
            blogPublishedByBlogId.DisLikeDisabled = Convert.ToBoolean(getblogPublishedByBlogIdReader["DisLikeDisabled"]);

            blogPublishedByBlogIdResults.BlogPublishedByBlogId = blogPublishedByBlogId;
        }

        return blogPublishedByBlogIdResults;
    }
    catch (SqlException sqlex)
    {                
        throw sqlex;
    }
    catch (Exception ex)
    {
    }
    finally
    {
        if (getblogPublishedByBlogIdReader != null)
        {
            getblogPublishedByBlogIdReader.Close();
        }

        dbFunc.CloseDB();
    }
}

使用史蒂夫代码的屏幕截图(相同的结果-从存储过程返回的LikeDisabled中的整数1仍被转换为值0):

enter image description here


使用史蒂夫代码的屏幕截图(相同的结果-从存储过程返回的LikeDisabled中的整数1仍被转换为0值)。另外,存储过程在带有调试选择的SSMS中运行。

enter image description here

enter image description here

解决方法

从逻辑上讲,它应该起作用。 唯一可能性是DisLikeDisabled在Db中为0。 您也可以为此使用替代

 blogPublishedByBlogId.LikeDisabled =(getblogPublishedByBlogIdReader["LikeDisabled"] == 1) ? True : False;
,

[编辑2],请尝试使用此修订方法(添加了变量以捕获SqlType):

public BlogPublishedByBlogIdResults GetBlogPublishedByBlogId(string userName,string ipAddress,int blogId,int userId)
    {
        BlogPublishedByBlogIdResults blogPublishedByBlogIdResults = new BlogPublishedByBlogIdResults();

        try
        {
            dbFunc.OpenDB();

            using (SqlCommand sqlCmd = new SqlCommand("dbo.GetBlogPublishedByBlogId",dbFunc.objConn))
            {
                sqlCmd.CommandType = CommandType.StoredProcedure;

                var uName = sqlCmd.Parameters.Add("@a_UserName",SqlDbType.VarChar,255);
                uName.Direction = ParameterDirection.Input;
                uName.Value = userName;
                var ipAddr = sqlCmd.Parameters.Add("@a_IpAddress",255);
                ipAddr.Direction = ParameterDirection.Input;
                ipAddr.Value = ipAddress;
                var blId = sqlCmd.Parameters.Add("@a_BlogId",SqlDbType.Int);
                blId.Direction = ParameterDirection.Input;
                blId.Value = userName;
                var uId = sqlCmd.Parameters.Add("@a_UserName",SqlDbType.Int);
                uId.Direction = ParameterDirection.Input;
                uId.Value = userName;

                using (var sqlDataReader = sqlCmd.ExecuteReader())
                {
                    while (sqlDataReader.Read())
                    {
                        // Get the SQL Server raw values by column offset
                        var sqlStatus = sqlDataReader.GetSqlInt32(0).Value;
                        var sqlBlogId = sqlDataReader.GetSqlInt32(1).Value;
                        var sqlBlogTitle = sqlDataReader.GetSqlString(2).Value;
                        var sqlBlogContent = sqlDataReader.GetSqlString(3).Value;
                        var sqlLikeCount = sqlDataReader.GetSqlInt32(4).Value;
                        var sqlDisLikeCount = sqlDataReader.GetSqlInt32(5).Value;
                        var sqlModDate = sqlDataReader.GetSqlDateTime(6).Value;
                        var sqlCreateDate = sqlDataReader.GetSqlDateTime(7).Value;
                        var sqlLikeDisabled = sqlDataReader.GetSqlInt32(8).Value;
                        var sqlDisLikeDisabled = sqlDataReader.GetSqlInt32(9).Value;

                        BlogPublishedByBlogId blogPublishedByBlogId = new BlogPublishedByBlogId();
                        blogPublishedByBlogIdResults.Status = Convert.ToInt32(sqlDataReader["Status"]);
                        blogPublishedByBlogId.BlogId = Convert.ToInt32(sqlDataReader["BlogId"]);
                        blogPublishedByBlogId.BlogTitle = sqlDataReader["BlogTitle"].ToString();
                        blogPublishedByBlogId.BlogContent = sqlDataReader["BlogContent"].ToString();
                        blogPublishedByBlogId.LikeCount = Convert.ToInt32(sqlDataReader["LikeCount"]);
                        blogPublishedByBlogId.DisLikeCount = Convert.ToInt32(sqlDataReader["DisLikeCount"]);
                        blogPublishedByBlogId.ModifiedDateTime = Convert.ToDateTime(sqlDataReader["ModifiedDateTime"]);
                        blogPublishedByBlogId.CreatedDateTime = Convert.ToDateTime(sqlDataReader["CreatedDateTime"]);

                        // Test code to see what the value is before trying to convert to boolean below.
                        int likeDisabled = Convert.ToInt32(sqlDataReader["LikeDisabled"]);
                        int DislikeDisabled = Convert.ToInt32(sqlDataReader["DisLikeDisabled"]);

                        blogPublishedByBlogId.LikeDisabled = Convert.ToBoolean(sqlDataReader["LikeDisabled"]);
                        blogPublishedByBlogId.DisLikeDisabled = Convert.ToBoolean(sqlDataReader["DisLikeDisabled"]);

                        blogPublishedByBlogIdResults.BlogPublishedByBlogId = blogPublishedByBlogId;
                    }
                    return blogPublishedByBlogIdResults;
                }
            }
        }
        catch (SqlException sqlex)
        {
            throw sqlex;
        }
        catch (Exception ex)
        {
        }
        finally
        {
            if (getblogPublishedByBlogIdReader != null)
            {
                getblogPublishedByBlogIdReader.Close();
            }

            dbFunc.CloseDB();
        }
    }

您可以尝试使用系统数据类型库。 SqlInt32不会转换为CLR布尔值。将整数作为SqlBoolean返回要容易得多。这是它的实际目的,因为没有BIT这样的“ SQL Boolean”。无论如何,类型库是一个完整的主题。从Sql类型到CLR类型的转换需要进行测试以确保其不为空。

using System.Data.SqlTypes;

然后从DataReader显式转换。如果您知道该值永远不会为空,则可以使用

var yourVar = (bool)sqlDataReader.GetSqlBoolean(0);

如果可以为空,则可以使用

var x = sqlDataReader.GetSqlBoolean(0).IsNull ? false : (bool)sqlDataReader.GetSqlBoolean(0);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res