简体   繁体   中英

set column to 'not null' in SQL Server

I have a column in a table in a sql server database that I want to set to 'not null'. However, when I execute the query

ALTER TABLE mytable ALTER COLUMN mycolumn INT NOT NULL 

I get an

ALTER TABLE ALTER COLUMN mycolumn failed because one or more objects access this column.

How can I find out what kind of object that is and how do I drop it? The database is very simple and is not supposed to make use of foreign keys, triggers etc.

You could search the sys tables to find out what is dependent on the column. This has its limitations, naturally, but by-and-large should give you some indication of what is dependent on your column:

SELECT
     OBJECT_NAME(D.Object_ID) AS [Dependent]
    ,D.Object_ID
FROM sys.sql_dependencies D
INNER JOIN sys.Columns C
    ON C.object_id = D.referenced_major_id
    AND C.column_id = D.referenced_minor_id
WHERE OBJECT_NAME(C.object_id) = 'MyTable'
AND C.name = 'MyColumn'
;

Once you have the name and object_id of the dependent (it might be a function, a stored procedure, or any number of things) you can go from there.

You might have to drop constraints on the column first,before altering this table.This may be a constraint,index or any thing..below is a small demo showing the same

create table #test
(
id int,
id1 int
)

create index nci_t on #test(id1)
include(id)

alter table #test
alter column id1 varchar(10)

this is the error i got

Msg 5074, Level 16, State 1, Line 2
The index 'nci_t' is dependent on column 'id1'.
Msg 4922, Level 16, State 9, Line 2
ALTER TABLE ALTER COLUMN id1 failed because one or more objects access this column.

also please paste entire error message ,don't strip it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM