且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中检查在SQL Server 2008 R2上是否存在我的表?

更新时间:2023-02-04 22:49:10

尝试以下方法.
下面的存储过程将表名作为参数,并根据表是否存在于数据库中而返回true或false.
Try the below approach.
The below stored procedure takes the table name as a parameter and returns true or false based on whether the table exists in database or not.
CREATE PROCEDURE usp_CheckTableExists
@TableName VARCHAR(50)
AS
BEGIN

    DECLARE @TableExists BIT

    IF EXISTS (SELECT 1 FROM Information_SCHEMA.Tables WHERE TABLE_NAME = @TableName)
    BEGIN
        SET @TableExists = 1
    END
    ELSE
    BEGIN
        SET @TableExists = 0
    END

    SELECT @TableExists AS TableExists

END



您可以在应用程序中获取此SP的结果,并使用它来决定是创建表还是仅向表中插入数据(如果表已存在).



You can take the result of this SP in your application and use it decide whether to create a table or just insert data into the table (if the table already exists).

bool TableExists;
using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    using (SqlCommand command = new SqlCommand("usp_CheckTableExists"))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add(new SqlParameter("@TableName", tableName));
                        connection.Open();
                        command.Connection = connection;
                        TableExists = (bool)(command.ExecuteScalar());
                        connection.Close();


                    }


                }

if(TableExists)
{
    //Table already exists in database
}
else
{
    //Table does not exist in database
}


bool isExists;  
  const string sqlStatement = @"SELECT COUNT(*) FROM customtablename";   
  try   
  {      
  using (SqlCommand command= new SqlCommand (sqlStatement, sqlConn)) 
       {  
           command.ExecuteScalar();   
          isExists= true; 
       }    
 }    
 catch  
   {    
     isExists= false;  
   } 



检查以上内容是否解决了您的问题



check if the above solves your problem


SELECT 
COUNT(1) 
FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[YourSchema].[YourTableName]') AND type in (N'U')




将[YourSchema].[YourTableName]替换为您喜欢的任何变量.
例如:可以将[dbo].[Mydata]用于[YourSchema].[YourTableName]

使用OLEDB的ExecuteScalar并检查计数> 0表示存在/不存在
例如:




Replace the [YourSchema].[YourTableName] with any variable you like.
For example : You can use [dbo].[Mydata] for [YourSchema].[YourTableName]

Use ExecuteScalar of OLEDB and check count > 0 for exist/doesnt exist
For example:

bool exist = (Int32)cmd.ExecuteScalar()==1 ? true: false ;