Search code examples
c#sqlconnection

Using Variables in SQL Query Run Through Code


I want to pass a variable to a sql string being executed via C#. I am hitting a compile error tho, and I am not perfectly sure how to end my sql statement with my variable. This is the line of code that I have

string Fire = "Database";
SqlConnection conn = new SqlConnection(connectSQL);
SqlCommand("IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = Main_'" + Fire + "') DROP VIEW dbo.Main_'" + Fire + "');

The errors are

Newline in constant
; expected
) expected

What do I need to do so that this becomes a valid statement?


Solution

  • You are missing the closing double quote. See below.

    SqlCommand("IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = Main_'" + Fire + "') DROP VIEW dbo.Main_'" + Fire + "'**"**);