I am trying to store encrypted data into my database (run by MS SQL 2005 Express) using stored procedure.
The stored procedure has the following signature:
ALTER PROCEDURE [dbo].[SaveData]
@FileName AS NVARCHAR(255),
@Data As VARBINARY(MAX),
@Key AS VARBINARY(MAX) = NULL,
@Final AS BIT = NULL
AS
....
In my code I have two variables of type byte[]
with my data:
public byte[] EncryptedData { get; set; }
public byte[] EncryptedPassword { get; set; }
var cmd = new SqlCommand("SaveData", conn);
cmd.CommandTimeout = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarBinary, EncryptedData.Length, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Current, (SqlBinary) EncryptedData));
cmd.Parameters.Add(new SqlParameter("@Key", SqlDbType.VarBinary, EncryptedPassword.Length, ParameterDirection.Input, false, 0, 0, "", DataRowVersion.Current, (SqlBinary)EncryptedPassword));
cmd.Parameters.AddWithValue("@Final", true);
Whenever I try to call ExecuteNonQuery()
I get the following error message (sorry for German, I just wanted to provide the original text, I also provide translation below!):
Falsche Syntax in der Nähe von '¿'.
Bezeichner (beginnend mit '*è ¯äÅõ42‹áºªž(±Z¦ññú>¬ÕÕ]¥Qî)ÀÍE5 Fäø+ïµ1˜Z}»[–A[Åñ#šužÿÄ}µ} %ãVð>TÛ¨¡ªƒ·g·SWFW
Here is the English translation of the error message (done by me, so it might and will deviate from the canonic original error message):
Syntax error near '¿'.
Identifier (beginning with '*è ¯äÅõ42‹áºªž(±Z¦ññú>¬ÕÕ]¥Qî)ÀÍE5 Fäø+ïµ1˜Z}»[–A[Åñ#šužÿÄ}µ} %ãVð>TÛ¨¡ªƒ·g·SWFW
It seems as if the SQL string is parsed incorectly and some binary data is parsed as an identifier name.
I tried many different approaches here using .AddWithValue()
and setting parameter properties one by one -- this doesn't help.
Any suggesions?
The solution was already pointed out in the comments, so I just answer the question here.
The problem was in using dynamic SQL (the concatenation of SQL strings) in the stored procedure, here is an example:
select @sql = 'insert into dbo.DMSFileData ('
...
select @sql = @sql + ') VALUES ('
select @sql = @sql + '''' + @FileName + ''''
select @sql = @sql + '''' + convert(varchar(max), @Data) + ''''
The correct solution here is to use parameters in concatenation:
select @sql = @sql + ', @filename'
select @sql = @sql + ', @filedata'
And then execute SQL using sp_executesql
:
exec sp_executesql @sql, @params, @ForeignKey, @FileName, @Data