What should I do if I want to determine whether a primary key exists in the table that adds a column or whether a field exists? The following describes how to write SQL statements to implement this function for your reference.
AD:
The SQL statements described below can determine whether a field exists and whether a primary key exists in the table where the column is added. These SQL statements are of practical value, we hope that you will have a better understanding of SQL statements.
- -- Determines whether the table to be added has a primary key.
- If exists (select 1 from sysobjects where parent_obj = object_id ('tb') and xtype = 'pk ')
- Begin
- Print 'The table already has a primary key, and the column can only be added as a normal column'
- -- Add an int column. The default value is 0.
- Alter table tb add column name int default 0
- End
- Else
- Begin
- Print 'table with no primary key, add primary key column'
- -- Add an int column. The default value is 0.
- Alter table tb add column name int primary key default 0
- End
- /*************************************** **************************************** *******/
- Determine whether the name field exists in table1
- If exists (select * from syscolumns where id = object_id ('table1') and name = 'name') begin
- Select * from people;
- End
-
- Determine whether the name field exists in table1 and delete the field
- If exists (select * from syscolumns where id = object_id ('table1') and name = 'name') begin
- Select * from people;
- Alter table table1 drop column name
- End
[Edit recommendations]
SQL statement for adding fields to a table
How to modify SQL Xml Fields
SQL statement used to query XML data
SQL defines Xml Fields
SQL Server table-related statements