可以在 C# 中复制 SQL Server 压缩吗?

问题描述 投票:0回答:1

如何复制可在 SQL 插入查询中使用的

Compress
功能?

我知道我可以做到以下几点:

INSERT INTO Player ([Name], [Surname], [Info])     
VALUES ('John', 'Smith', COMPRESS(N'{"sport":"Tennis","age": 28,"rank":1,"points":15258, turn":17}'))

但是有没有办法在 C# 中复制 T-SQL

Compress
方法,本质上是在插入数据库之前压缩代码,然后能够在 SQL 读取查询中解压缩它?

我尝试了以下代码的多种变体:

private readonly string _insertQuery =
    @"INSERT INTO Player([Name],[Surname],[Info]) 
      OUTPUT INSERTED.Id, inserted.Info
      VALUES(?,?,?)";

public void CompressAndWriteToDB()
{
    using OleDbConnection connection = new(_connectionString);

    OleDbCommand cmd = new OleDbCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = _insertQuery;

    cmd.Parameters.Add(new OleDbParameter("@name", "John"));
    cmd.Parameters.Add(new OleDbParameter("@surname", "Smith"));

    var uncompressedString = "{\"sport\":\"Basketball\",\"age\": 45,\"rank\":1,\"points\":15258, turn\":17}";
    var bytes = Encoding.UTF8.GetBytes(uncompressedString);

    using (var memoryStream = new MemoryStream())
    {
        using (var gzipStream = new GZipStream(memoryStream, CompressionLevel.Optimal))
        {
            gzipStream.Write(bytes, 0, bytes.Length);
        }
        var param = cmd.Parameters.Add("@info", SqlDbType.VarBinary);
        param.Value = memoryStream.ToArray();
    }

    cmd.Connection = connection;

    connection.Open();

    cmd.ExecuteReader();
}

但是当我尝试使用 T-SQL

Decompress
方法解压缩 SSMS 中的数据时,我只得到奇怪的字符:

enter image description here

c# sql-server compression
1个回答
0
投票

我把这个答案归功于@AlwaysLearning。谢谢!

基本上,使用与原始帖子中完全相同的代码,我只需将

Encoding.UTF8
更改为
Encoding.Unicode

var bytes = Encoding.Unicode.GetBytes(uncompressedString);

现在我可以访问 SSMS 中的数据并使用

解压缩
  SELECT [Id]
  ,[Name]
  ,[Surname]
  ,Info
  ,CAST(DECOMPRESS(Info) AS NVARCHAR(MAX)) AS  AfterCastingDecompression
  FROM [MCrockett].[dbo].[Player]
  WHERE Id = 9
© www.soinside.com 2019 - 2024. All rights reserved.