SQL CE Dynamic Query

人走茶凉 提交于 2019-12-25 03:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!