如何在添加新列时检查列名是否存在。 [英] How to check whether column name exist while adding a new column.

查看:54
本文介绍了如何在添加新列时检查列名是否存在。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了下面的sql查询来向表中添加一个列。

但是我想首先找到是否有任何现有列具有相同的名称,我不知道该怎么做。

我在Try-Catch语句中放了comm.ExecuteNonQuery() - 因为当列名存在时它会给出异常。

我这样做是对吗???



还有一个问题:当写下面的sql时,它会创建数据类型的列:是/否,这就是我想要的但它取值0 / -1但是我必须检查是否为真/假。



I wrote following sql query to add a column to a table.
but i want to find first whether any existing column has the same name which i dont know how to do.
I have put "comm.ExecuteNonQuery()" in Try-Catch statement- as it give exception when column name exist.
Am i doing it correct???

One more question : When writing following sql it creates column with data type:yes/No, this is what i want but it takes value 0/-1 but i have to check for true/false.

ConnectionToDB();
string sql = "ALTER TABLE table_name ADD Proj bit";
comm.CommandType = CommandType.Text;
comm.CommandText = sql;
comm.Connection = conn;
conn.Open();
comm.ExecuteNonQuery();
conn.Close();





提前致谢



Thanks in advance

推荐答案

您好b $ b

此链接可能是您的解决方案





http://stackoverflow.com/questions/133031/how- to-check-if-column-exists-in-sql-server-table [ ^ ]
Hi
This link may be the solution for you


http://stackoverflow.com/questions/133031/how-to-check-if-column-exists-in-sql-server-table[^]


你好试试这个

Hello Try this
If Not Exists(Select b.name from sysObjects a , syscolumns b 
where b.id = a.Id and a.Type ='U' and b.name = 'columnname' 
and a.name = 'tblname')
	Begin
		ALTER TABLE tblname ADD columnname INT 
	End
GO





谢谢



thanks






检查一下...... SQL Server中是否存在数据库/表/列 [ ^ ]



但是......你为什么要通过代码执行呢?





希望这会对你有所帮助



干杯
Hi,

Check this...Does a Database/Table/Column Exist in SQL Server[^]

But still....why do you want to perform it through code?


Hope this will help you

Cheers


这篇关于如何在添加新列时检查列名是否存在。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆