please can anyone point me in the right direction. I want to check if the column exists, if so do this select else do another select
select case
when exists (
SELECT *
FROM Sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')
AND c.name = 'AmountTypeLabel'
)
then 1
else 0
end
This Checks if column exists and then return a 0 or a 1 but there is no column name so i can't check it in C#
This is what i have tried in C# but as i said before there is no column name
DataTable DT;
string SQL = "";
try
{
SQL = "select case " +
" when exists( " +
" SELECT 1 " +
" FROM Sys.columns c " +
" WHERE c.[object_id] = OBJECT_ID('dbo.Municipality')" +
" AND c.name = 'AmountTypeLabel'" +
")" +
" then 1 " +
" else 0 " +
" end ";
DT = Conn.ExecuteDT(SQL);
}
catch (Exception ex)
{
throw new Exception("Unable to get Tables", ex);
}
return DT;
}
With existing code you can fetch the value by using the below and use it in another function:
if(DT.Rows[0][0].ToString() == "1")
//Do Something
OR you could to use SQL Alias
in your SQL query like below:
" end AS ColumnExists";
and then you can refer this in your other function. Sample snippet below -
if(DT.Rows[0]["ColumnExists"].ToString() == "1")
//Do Something
On a side note
if the requirement is to fetch only the 1 or 0
from SQL server then use the ExecuteScalar
as mentioned by Matteo1010 in comments.
var columnExists = cmd.ExecuteScalar();
if(columnExists.ToString() == "1")
//Do Something
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.