Click here to Skip to main content
15,889,820 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to check if a value exists in a DB table and return a Boolean value to variable in vb.net??
Posted

you can create a function like this and execute the function to get your desired output

SQL
create function fnCheckExists()
returns bit
as
begin
declare @val as bit=0;
if exists (select yourColumn from yourTable)
begin
 set @val=1;
end
else
begin
 set @val=0;
end
return @val
end
 
Share this answer
 
Comments
Oshtri Deka 3-Sep-12 4:02am    
You are checking if there is any record inside a table.
I believe OP wants to check for particular values.
Hi Try like this

C#
private void Form4_Load(object sender, EventArgs e)
      {
          int Company_Id = 3;
          Boolean id = Convert.ToBoolean(existCompanyId(Company_Id));
      }

public int existCompanyId(int Company_Id)
{
 
 string SQLConnectionStr = "Password=password;Connection Timeout=0;Persist Security
   Info=False;User ID=userid;Initial Catalog=databasename;Data Source=servername;";
 SqlConnection sqlConnection = new SqlConnection(SQLConnectionStr);
 int CId;

 string TableExists = "IF EXISTS (select * from Company WHERE CompanyId ='" +  
 Company_Id + "') select 1 ELSE select 0";
            
try
  {
   using (SqlConnection spContentConn = new SqlConnection(SQLConnectionStr))
  {
   spContentConn.Open();
   using (SqlCommand TableExistsQry = new SqlCommand(TableExists, spContentConn))
   {
    TableExistsQry.CommandTimeout = 0;
    TableExistsQry.CommandType = CommandType.Text;
    CId = System.Convert.ToInt32(TableExistsQry.ExecuteScalar());
   }
     spContentConn.Close();
  }
    return CId;
 }
 catch (Exception ex)
  {
   throw ex;
  }
}


If the Company Id 3 exists in the table we will get id as true other wise id as false.
 
Share this answer
 
v2
Comments
dmunisubbu 3-Sep-12 3:52am    
fine 4+
D-Kishore 3-Sep-12 3:59am    
Thank you dmunisubbu

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900