Search code examples
sqlsql-servernvarcharunique-index

SQL Server unique index on nvarchar issue


I have a SQL Server table with a nvarchar(50) column. This column must be unique and can't be the PK, since another column is the PK. So I have set a non-clustered unique index on this column.

During a large amount of insert statements in a serializable transaction, I want to perform select queries based on this column only, in different transaction. But these inserts seem to lock the table. If I change the datatype of the unique column to bigint for example, no locking occurs.

Why isn't nvarchar working, whereas bigint does? How can I achieve the same, using nvarchar(50) as the datatype?


Solution

  • After all, mystery solved! Rather stupid situation I guess..

    The problem was in the select statement. The where clause was missing the quotes, but due to a devilish coincidence of the existing data were only numbers, the select wasn't failing but just wasn't executing until the inserts committed. When the first alphanumeric data were inserted, the select statement begun failing with 'Error converting data type nvarchar to numeric'

    e.g Instead of

    SELECT [my_nvarchar_column]  
    FROM [dbo].[my_table]  
    WHERE [my_nvarchar_column] = '12345'
    

    the select statement was

    SELECT [my_nvarchar_column]  
    FROM [dbo].[my_table]  
    WHERE [my_nvarchar_column] = 12345
    

    I guess a silent cast was performed, the unique index was not being used which resulted to the block. Fixed the statement and everything works as expected now.

    Thanks everyone for their help, and sorry for the rather stupid issue!