title: MS SQL Server EncryptByKey - String or binary data would be truncated
body: <p>In theory <code>varchar(max)</code> and <code>varbinary(max)</code> columns should be capable of storing  up to 2GB of data but I cannot store a unicode string 5000 characters long.</p>
  
  <p>I've looked through other questions on this topic and they all suggest checking column sizes. I've done this and see that all related columns are declared with max size.</p>
  
  <p>The key difference from similar questions is that, when storing I'm encrypting data using <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/encryptbykey-transact-sql?view=sql-server-2017" rel="nofollow noreferrer"><code>EncryptByKey</code></a> and I think that it's the bottleneck I'm looking for. From MSDN I know that return type of <code>EncryptByKey</code> has max size of 8000 bytes, and it is not clear what is max size of  <code>@cleartext</code> argument, but I suspect it's the same.</p>
  
  <p>The following code gives me error :</p>
  
  <pre><code>OPEN SYMMETRIC KEY SK1 DECRYPTION BY CERTIFICATE Cert1;
  
  DECLARE @tmp5k AS NVARCHAR(max);
  SET @tmp5k = N'...5000 characters...';
  SELECT EncryptByKey(Key_GUID('SK1'), @tmp5k);
  GO
  </code></pre>
  
  <blockquote>
    <p>[22001][8152] String or binary data would be truncated.</p>
  </blockquote>
  
  <p>How to encrypt and store big strings (around 5k unicode characters)?</p>