SQL Server 2008 Foreign Keys case sensitivity

前端 未结 3 2073
-上瘾入骨i
-上瘾入骨i 2021-01-16 10:01

Is it possible for SQL Server 2008 to have case insensitive data, for instance the following would return data...

SELECT mycolumn FROM mytable WHERE mycolumn         


        
3条回答
  •  时光取名叫无心
    2021-01-16 10:56

    If you want the foreign key to be case sensitive, then just set the column to be case sensitive (and make sure that the key it references uses the same collation). Borrowing the collation from Michael's answer:

    USE tempdb;
    GO
    
    CREATE TABLE dbo.foo 
    ( 
      [key] VARCHAR(32) COLLATE SQL_Latin1_General_CP1_CS_AS
      PRIMARY KEY
    );
    
    CREATE TABLE dbo.bar 
    (
      [key] VARCHAR(32) COLLATE SQL_Latin1_General_CP1_CS_AS
      FOREIGN KEY REFERENCES dbo.foo([key])
    );
    
    INSERT dbo.foo SELECT 'Bob';
    INSERT dbo.foo SELECT 'bOB';
    INSERT dbo.foo SELECT 'BOB';
    GO
    
    -- fails:
    INSERT dbo.bar SELECT 'bob';
    GO
    
    -- succeeds:
    INSERT dbo.bar SELECT 'Bob';
    GO
    

    If you want queries against the same column to be case insensitive, you can just specify a COLLATE clause (note it contains _CI_ instead of _CS_):

    SELECT COUNT(*) FROM dbo.foo 
      WHERE [key] = 'Bob';
    
    ----
    1
    
    SELECT COUNT(*) FROM dbo.foo 
      WHERE [key]  COLLATE SQL_Latin1_General_CP1_CI_AS = 'Bob';
    
    ----
    3
    

提交回复
热议问题