如何使用内联查询在 SQL Server 中插入 unicode 字符

本文关键字:Server 插入 unicode 字符 SQL 何使用 查询 | 更新日期: 2023-09-27 18:37:27

我在 asp.net 中使用内联查询,但问题是我现在不知道如何正确使用 N 后缀请指导....

  cn.Open();
    SqlCommand cmd = new SqlCommand("insert into newsactivity VALUES(@newstitle, @newsdetails ,@dated,@type)",cn);
    cmd.Parameters.AddWithValue("@newstitle",txtnewstitle.Text);
    cmd.Parameters.AddWithValue("@newsdetails",N'txtnewsdetails.Text');

如何使用内联查询在 SQL Server 中插入 unicode 字符

说应该就够了

cmd.Parameters.AddWithValue("@newsdetails", txtnewsdetails.Text);

编辑:如果失败,那么这应该有效:

cmd.Parameters.Add("@newsdetails", SqlDbType.NVarChar, 1024).Value = txtnewsdetails.Text;

你不需要。 .NET 字符串已经是 unicode。N 只是告诉查询分析器,N 后面的字符串文本是 Unicode。

例如

cmd.Parameters.AddWithValue("@newsdetails","मैं stackoverflow प्यार है");

只需确保newsactivity表中的字段newsdetails NVARCHAR(..)

编辑这很奇怪。可能 AddWithValue 没有正确推断参数的类型。您可以显式指定它:

SqlParameter param = cmd.Parameters.AddWithValue("@newsdetails",txtnewsdetails.Text);
param.SqlDbType = SqlDbType.NVarChar;

显式指定类型和长度的另一个很好的理由是,如果在 WHERE 子句筛选器中使用该参数。请参阅没有 DBType 导致查询运行缓慢的 AddWithValue

参数中使用SqlDbType.NVarChar