问题
One of my database tables in SQL CE 3.5 has a primary key. I want to alter the column in the primary key to expand it from an nvarchar(7) to nvarchar(20).
Do I absolutely need to drop the primary key to achieve this?
How can I drop the primary key with a script if I do not know the name of the primary key?
The name is PK__sign_type__000000000000228E for example so it has been generated dynamically.
I have 200 or 300 of these databases on our clients machines and a generic script is necessary as they will all have different names for this primary key.
回答1:
First query INFORMATION_SCHEMA.COLUMNS to see if the change is required:
SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Shippers'
AND COLUMN_NAME = 'Company Name'
Then get the constraint name from the table like this:
SELECT DISTINCT c.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS c INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS u ON c.CONSTRAINT_NAME = u.CONSTRAINT_NAME AND u.TABLE_NAME = c.TABLE_NAME
where c.CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = 'Shippers'
Then you can construct the primary key drop and alter the column.
Remember to give the primary key a proper name when you recreate.
来源:https://stackoverflow.com/questions/24879338/sql-ce-dynamic-query