Task:
Replace certain variables within an sql statement with the requisite data.
Issue:
The variables are not being replaced
C# code:
SqlCommand cmd = new SqlCommand(@"
select
1 [GL],
(
select
isnull(COUNT(*), 0)
from
@DataDB..APSetup
) [AP],
(
select
isnull(COUNT(*), 0)
from
@DataDB..ARSetup
) [AR],
(
select
isnull(COUNT(*), 0)
from
@DataDB..CASetup
) [CA],
case
when (
select
isnull(COUNT(*), 0)
from
@DataDB..SalesTax
) > 0
then 1 else 0
end [TX],
(
select
isnull(COUNT(*), 0)
from
@DataDB..INSetup
) [IN],
(
select
isnull(COUNT(*), 0)
from
@DataDB..POSetup
) [PO],
(
select
isnull(COUNT(*), 0)
from
@DataDB..SOSetup
) [SO],
(
select
isnull(COUNT(*), 0)
from
@DataDB..RQSetup
) [RQ],
(
select
COUNT(*)
from
@DataDB..pcsetup
Where
Setupid = 'PC' AND PERNBR <> ''
) [PJ]
from
@DataDB..glsetup");
cmd.Parameters.AddWithValue("@DataDB", CurrentBranch.AppDB);
AppConnection.InitialCatalog = CurrentBranch.AppDB;
Modules.AddRange(SqlQueries.DataQuery2(cmd, AppConnection.ConnectionString));
Sql Query:
select 1 [GL], (select isnull(COUNT(*),0) from @DataDB..APSetup) [AP], (select isnull(COUNT(*),0) from @DataDB..ARSetup) [AR], (select isnull(COUNT(*),0) from @DataDB..CASetup) [CA], case when (select isnull(COUNT(*),0) from @DataDB..SalesTax) > 0 then 1 else 0 end [TX], (select isnull(COUNT(*),0) from @DataDB..INSetup) [IN], (select isnull(COUNT(*),0) from @DataDB..POSetup) [PO], (select isnull(COUNT(*),0) from @DataDB..SOSetup) [SO], (select isnull(COUNT(*),0) from @DataDB..RQSetup) [RQ], (select COUNT(*) from @DataDB..pcsetup Where Setupid = 'PC' AND PERNBR <> '') [PJ] from @DataDB..glsetup
Question:
Why does the variable replacement not work?
Additional Information:
The issue is not the query, when I manually replace the @DataDB with its intended value it works fine.
The issue is the C# SqlCommand.Parameters.AddWithValue();
The reason is because you can’t parameterize what database/table you are trying to select from. You can’t do:
select * from @SomeTableYou already are doing this in C#, just do this:(snipped for clarity sake):