zoukankan      html  css  js  c++  java
  • nvarchar(max) still being truncated

    nvarchar(max) still being truncated

    The problem is with implicit conversion.

    If you have Unicode/nChar/nVarChar values you are concatenating, then SQL Server will implicitly convert your string to nVarChar(4000), and it is unfortunately too dumb to realize it will truncate your string or even give you a Warning that data has been truncated for that matter!

    When concatenating long strings (or strings that you feel could be long) always pre-concatenate your string building with CAST('' as nVarChar(MAX)) like so:

    SET @Query = CAST('' as nVarChar(MAX))--Force implicit conversion to nVarChar(MAX)
               + 'SELECT...'-- some of the query gets set here
               + '...'-- more query gets added on, etc.
    

    What a pain and scary to think this is just how SQL Server works. :(

    I know other workarounds on the web say to break up your code into multiple SET/SELECT assignments using multiple variables, but this is unnecessary given the solution above.

    For those who hit an 8000 character max, it was probably because you had no Unicode so it was implicitly converted to VarChar(8000).

    Explanation:
    What's happening behind the scenes is that even though the variable you are assigning to uses (MAX), SQL Server will evaluate the right-hand side of the value you are assigning first and default to nVarChar(4000) or VarChar(8000) (depending on what you're concatenating). After it is done figuring out the value (and after truncating it for you) it then converts it to (MAX) when assigning it to your variable, but by then it is too late.

    Why Is My VARCHAR(MAX) Variable Getting Truncated? 

            Instead, I recommend casting a blank as VARCHAR(MAX) and prefixing it to the start of your variable string.  Leave yourself a comment for the future and hopefully you'll remember why this superfluous looking piece of code is needed:

    -- using CAST('') to force SQL to define
    -- as varchar(MAX)
    SET @dynamicQuery =  CAST('' AS varchar(MAX))
        + REPLICATE('a',8000)+ 'b'
    
  • 相关阅读:
    python 字典转对象实现
    漏洞复现的整理
    mlx90614红外传感器
    【小程序码】登录的技术实现案例
    Spring mvc Aop
    MSHFLEXGRID常用的属性,方法事件
    InsertAuditEntryNew
    Froggy 的 CSP-2021 S1 游记
    JOI Open 偷学记录
    生产订单工序新增、修改、删除——CO_SE_PRODORD_OPR_CREATE、CO_SE_PRODORD_OPR_CHANGE、CO_SE_PRODORD_OPR_DELETE
  • 原文地址:https://www.cnblogs.com/chucklu/p/14519530.html
Copyright © 2011-2022 走看看