Answer the question
In order to leave comments, you need to log in
Declare to pass variable in SQL query?
Hello!
The question is how to pass a variable in a sql query to a construct?
declare
a int;
b int;
BEGIN
SELECT city.city_id into a FROM city WHERE city.name = 'Миасс';
SELECT city.city_id into b FROM city WHERE city.name = 'Плесецк';
INSERT INTO FIRM(FIRM_ID, NAME, POST_CITY_ID, JUR_CITY_ID) VALUES(supplier_seq.NEXTVAL, 'Спутник', a, b);
COMMIT;
end;
String sql = "INSERT INTO FIRM(FIRM_ID, NAME, POST_CITY_ID, JUR_CITY_ID) " +
"VALUES(supplier_seq.NEXTVAL, :NAME, :POST_CITY_ID, :JUR_CITY_ID)";
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("NAME", OracleDbType.Varchar2, 25).Value = CityNameTextBox.Text.ToString();
cmd.Parameters.Add("POST_CITY_ID", OracleDbType.Varchar2, 25).Value = CityNameJurTextBox.Text.ToString();
cmd.Parameters.Add("JUR_CITY_ID", OracleDbType.Varchar2, 25).Value = CityNamePostTextBox.Text.ToString();
OracleDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
var v = dt.HasErrors;
myDataGrid.ItemsSource = dt.DefaultView;
dr.Close();
this.SqlAddFirmTable = "declare " +
" a int; " +
" b int; " +
" BEGIN" +
" SELECT city.city_id into a FROM city WHERE city.name = :POST_CITY_ID; " +
" SELECT city.city_id into b FROM city WHERE city.name = :JUR_CITY_ID; " +
" INSERT INTO FIRM(FIRM_ID, NAME, POST_CITY_ID, JUR_CITY_ID) VALUES(supplier_seq.NEXTVAL, :NAME, a, b); " +
" COMMIT; " +
" end;";
query = String.Format("declare" +
" a int;" +
" BEGIN" +
" SELECT count(city.city_id) into a FROM city WHERE city.name = '{0}';" +
" if a = 0 THEN" +
" insert into city(CITY_ID, NAME) values(supplier_seq.NEXTVAL, '{0}');" +
" end if;" +
" SELECT city.city_id into a FROM city WHERE city.city_id =(select min(city.city_id) from city where city.name = '{0}');" +
" INSERT INTO FIRM(FIRM_ID, NAME, JUR_CITY_ID) VALUES(supplier_seq.NEXTVAL, '{2}', a);" +
" COMMIT;" +
" end; ", JUR_CITY, POST_CITY, NAME);
Answer the question
In order to leave comments, you need to log in
The answer couldn't be simpler:
query = String.Format("declare" +
" a int;" +
" BEGIN" +
" SELECT count(city.city_id) into a FROM city WHERE city.name = '{0}';" +
" if a = 0 THEN" +
" insert into city(CITY_ID, NAME) values(supplier_seq.NEXTVAL, '{0}');" +
" end if;" +
" SELECT city.city_id into a FROM city WHERE city.city_id =(select min(city.city_id) from city where city.name = '{0}');" +
" INSERT INTO FIRM(FIRM_ID, NAME, JUR_CITY_ID) VALUES(supplier_seq.NEXTVAL, '{2}', a);" +
" COMMIT;" +
" end; ", JUR_CITY, POST_CITY, NAME);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question