SQL statement for determining whether a field exists

Source: Internet
Author: User

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.

  1. -- Determines whether the table to be added has a primary key.
  2. If exists (select 1 from sysobjects where parent_obj = object_id ('tb') and xtype = 'pk ')
  3. Begin
  4. Print 'The table already has a primary key, and the column can only be added as a normal column'
  5. -- Add an int column. The default value is 0.
  6. Alter table tb add column name int default 0
  7. End
  8. Else
  9. Begin
  10. Print 'table with no primary key, add primary key column'
  11. -- Add an int column. The default value is 0.
  12. Alter table tb add column name int primary key default 0
  13. End
  14. /*************************************** **************************************** *******/
  15. Determine whether the name field exists in table1
  16. If exists (select * from syscolumns where id = object_id ('table1') and name = 'name') begin
  17. Select * from people;
  18. End
  19.  
  20. Determine whether the name field exists in table1 and delete the field
  21. If exists (select * from syscolumns where id = object_id ('table1') and name = 'name') begin
  22. Select * from people;
  23. Alter table table1 drop column name
  24. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.