2

I am using a new SQL Server 2016 feature - Always Encrypted. It is very cool and simple technology - but not for decimal type.

When I insert a value, I am getting errors like this one (ZP_Test - my DB name):

Operand type clash: decimal(4,2) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'ColomnKey', column_encryption_key_database_name = 'ZP_Test') is incompatible with decimal(18,2) encrypted with (encryption_type = 'RANDOMIZED', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'ColomnKey', column_encryption_key_database_name = 'ZP_Test')
Statement(s) could not be prepared.

My API is written in C#, please see my code maybe you know the solution.

SQL query for creating the table

CREATE TABLE [dbo].[EmpInfo]
(
    [EmpID] [int] NULL,
    [NatID] [nvarchar](max) COLLATE Cyrillic_General_BIN2 ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [ColomnKey], ENCRYPTION_TYPE = Randomized, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL,
    [Amount] [decimal](18, 2) ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = [ColomnKey], ENCRYPTION_TYPE = Randomized, ALGORITHM = 'AEAD_AES_256_CBC_HMAC_SHA_256') NULL
) ON [PRIMARY]
GO

C# code example

command.CommandText = "INSERT INTO EmpInfo(EmpID, NatID, Amount) VALUES (@key, @ssn, @amount)";

command.Parameters.AddWithValue("@key", key);
command.Parameters.AddWithValue("@ssn", DBNull.Value);
command.Parameters.AddWithValue("@amount", Convert.ToDecimal("11.00"));
command.ExecuteNonQuery();

Trace in SQL, when an error occurs -

exec sp_describe_parameter_encryption N'INSERT INTO EmpInfo(EmpID, NatID, Amount, AmountDec) VALUES (@key, @ssn, @amount, @amountDec)',N'@key int,@ssn nvarchar(7),@amount decimal(4,2)'
Jayesh Goyani
  • 11,008
  • 11
  • 30
  • 50

1 Answers1

0

Please specify the decimal's precision and scale using SqlParamater object as follows

SqlParameter param = new SqlParameter("@amount", SqlDbType.Decimal);
param.Precision = 18;
param.Scale = 2;
command.Parameters.Add(param);