1. How to determine whether a column exists in a table in Sql Server
First of all, I will share with you two methods for judging whether a column in a table exists in Sql Server. Examples of methods are as follows:
For example, to determine whether there are two methods for field C in table A:
the first method
1
2
3
4
5
6
7
8
|
IF EXISTS (
SELECT
1
FROM
SYSOBJECTS T1
INNER
JOIN
SYSCOLUMNS T2
ON
T1.ID=T2.ID
WHERE
T1.
NAME
=
'A'
AND
T2.
NAME
=
'C'
)
PRINT
'存在'
ELSE
PRINT
'不存在'
|
The second method, short and powerful, can be described as a classic
1
2
3
4
|
IF COL_LENGTH(
'A'
,
'C'
)
IS
NOT
NULL
PRINT N
'存在'
ELSE
PRINT N
'不存在'
|
method one:
1
|
select
*
from
syscolumns
where
id=object_id(
'表名'
)
and
name
=
'列名'
|
Description: Returns a description record of this column if it exists, returns null if it does not exist;
Method Two:
1
|
select
count
(*)
from
sysobjects a,syscolumns b
where
a.id=b.id
and
b.
name
=
'flag1'
and
a.type=
'u'
and
a.
name
=
'T_Pro_ProductClass'
|
Description: Returns 1 if it exists, returns 0 if it does not exist
2. Determine whether a table or column exists in Sql Server, and create it if it does not exist
1. Create the table if it does not exist:
1
2
3
4
5
6
7
8
9
10
|
if
not
exists (
select
*
from
sysobjects
where
id = object_id(
'mytab'
)
and
OBJECTPROPERTY(id,
'IsUserTable'
) = 1)
create
table
mytab
(
id
int
,
age
int
,
name
varchar
(
max
),
primary
key
(id,age)
)
go
|
2. If the column does not exist, create it.
1
|
if
not
exists (
select
*
from
syscolumns
where
id=object_id(
'mytab'
)
and
name
=
'columnname'
)
alter
table
[mytab]
add
columnname nvarchar(
max
)
|
Summarize
The above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Script Home.
Source: http://www.jb51.net/article/107305.htm