传输 ASCII(子)设置为 table

Transferring ASCII (sub)set to table

我正在尝试将 ASCII 字符的子集传输到 table,但我一直收到一条错误消息,提示我正在 SSMS 中复制值。

这是我的代码 table:

create table xyz(
  aChar char not null,
  primary key(aChar)
);

然后填充 table:

declare @xChars int = 250
declare @iterations int = 0
while @iterations < @xChars
begin
insert into xyz values (char(@iterations))
set @iterations += 1
end

希望你们中的一位能帮我解决这个问题。

问题是不区分大小写的排序规则。 'a''A' 是一回事。因此,使用区分大小写的排序规则:

create table xyz (
  aChar char collate SQL_Latin1_General_CP1_CS_AS not null,
  primary key(aChar)
);

您可以使用一条语句完成此操作:

with nums as (
      select 1 as n
      union all
      select n + 1
      from nums
      where n + 1 < 250
     )
insert into xyz (aChar)
    select char(nums.n)
    from nums
options (maxrecursion 0);

Here 是 SQL Fiddle.

您也可以使用计算列执行此操作:

create table xyz(
  aChar_num smallint not null,
  aChar as (char(aChar_num)),
  primary key(aChar_num)
);

with nums as (
      select 1 as n
      union all
      select n + 1
      from nums
      where n + 1 < 250
     )
insert into xyz (aChar_num)
    select nums.n
    from nums
    option (maxrecursion 0);

如图thisSQLFiddle.

SQL 服务器中的字符数据按排序规则存储。排序规则定义文本的排序顺序和相等性比较。默认排序规则不区分大小写,因此字符 'a' 和字符 'A' 比较相等。你在 aChar 上有一个唯一索引,所以你不能在列中存储 'a' 和 'A'。也可能有空格或不可打印的字符比较相等。

您想使用二进制排序规则声明该列,以便字符按其代码点而不是语言排序规则进行比较。例如

drop table if exists xyz
create table xyz(
  aChar char  collate Latin1_General_BIN2 not null,
  primary key(aChar)
);
go
declare @xChars int = 250
declare @iterations int = 0
while @iterations < @xChars
begin
insert into xyz values (char(@iterations))
set @iterations += 1
end