Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

sql - Why OBJECT_ID used while checking if a table exists or not

I need to check if a table in SQL exist or not.

If not it must create one automatically.

Now I researched and found this code:

IF  NOT EXISTS (SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[YourTable]') AND type in (N'U'))

BEGIN
CREATE TABLE [dbo].[YourTable](
....
....
....
) 

END

Can anyone explain why it says where object_id = OBJECT_ID and what should I put in its place?

question from:https://stackoverflow.com/questions/17546814/why-object-id-used-while-checking-if-a-table-exists-or-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I like this syntax:

if(object_id(N'[dbo].[YourTable]', 'U') is not null)
...

Where object_id takes the 2 char type of object as the second parameter. You can find the list of Object types listed below in the sys.objects documentation:

  • AF = Aggregate function (CLR)
  • C = CHECK constraint
  • D = DEFAULT (constraint or stand-alone)
  • F = FOREIGN KEY constraint
  • FN = SQL scalar function
  • FS = Assembly (CLR) scalar-function
  • FT = Assembly (CLR) table-valued function
  • IF = SQL inline table-valued function
  • IT = Internal table
  • P = SQL Stored Procedure
  • PC = Assembly (CLR) stored-procedure
  • PG = Plan guide
  • PK = PRIMARY KEY constraint
  • R = Rule (old-style, stand-alone)
  • RF = Replication-filter-procedure
  • S = System base table
  • SN = Synonym
  • SO = Sequence object
  • SQ = Service queue
  • TA = Assembly (CLR) DML trigger
  • TF = SQL table-valued-function
  • TR = SQL DML trigger
  • TT = Table type
  • U = Table (user-defined)
  • UQ = UNIQUE constraint
  • V = View
  • X = Extended stored procedure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...