问题
I know it's not a good idea, but I would like to double check that this won't do something crazy like crash the server.
CREATE TABLE [dbo].[Items](
[Id] [nvarchar](255) NOT NULL PRIMARY KEY,
[Value] [nvarchar](max) NOT NULL,
)
It would be interesting to know details about how a key like this compares to an [int] key, but just confirmation that this will not hurt anything is sufficient.
回答1:
Can you use VARCHAR(#) as a primary key?
Yes.
From the documentation, a VARCHAR(255) will take upwards of 257 (255+2) bytes (depends on the length of the actual data), for that column -- per row.
It would be interesting to know details about how a key like this compares to an
INTkey
INT takes 4 bytes, according to documentation. Depending on your data, there are numeric data types that take less space:
SMALLINT: 2 bytesTINYINT: 1 byte
The lower the number of bytes, the faster accessing data in the column will be. That includes JOINs. Additionally, the database (and backups) will be smaller.
I would greatly question the need for such a large VARCHAR as the primary key -- GUIDs aren't even that long.
回答2:
No, you can create a primary key on almost any SQL type. SQL will not allow it if it would crash the server. As you already stated, this will not be great for the server memory or performance, though.
In fact, here is the SO answer to the performance part of this question.
回答3:
There is a performance overhead with this, but it won't 'crash the server'.
来源:https://stackoverflow.com/questions/9780427/will-a-table-with-varchar255-primary-key-hurt-anything