This code shown here doesn't throw any errors, but also doesn't return any result. It should create 2 temp tables in tempDB
but doesn't because of passing the values to parameters with AddWithValue
.
Here is my code:
private void createTempTables(int sipID, int frmID)
{
const string str =
@"
BEGIN
IF OBJECT_ID('tempdb..#temp_sip1') IS NOT NULL
DRIO TABLE #temp_sip1;
WITH temp_sip AS
(
SELECT DISTINCT
ehID, ehSira, ehStkID, ehAdet, ehAdetN, ehTutar,
ehIndirim, ehKDV, ehi1, ehi2, ehi3, ehi4, ehi5, ehiT6, ehDurum,
ehTutarKDV, ehBirim, ehSevkAdet, ehTutarDvz,
ehSevkKontrol, ehNot, ehSipBag, ehAltStkID,
ROW_NUMBER() OVER (PARTITION BY ehStkID ORDER BY ehAdet DESC) AS rank
FROM
v_emp(@sipID, @frmID) //THIS PART.
)
SELECT *
INTO #temp_sip1
FROM temp_sip
WHERE rank = 1
IF OBJECT_ID('tempdb..#temp_sip2') IS NOT NULL
DROP TABLE #temp_sip2;
WITH temp_sip AS
(
SELECT DISTINCT
ehID,
ROW_NUMBER() OVER (PARTITION BY ehID ORDER BY ehStkID DESC) ehSira,
ehStkID, ehAdet, ehAdetN, ehTutar, ehIndirim,
ehKDV, ehi1, ehi2, ehi3, ehi4, ehi5, ehiT6,
ehDurum, ehTutarKDV, ehBirim, ehSevkAdet,
ehTutarDvz, ehSevkKontrol, ehNot, ehSipBag, ehAltStkID
FROM
#temp_sip1
)
SELECT *
INTO #temp_sip2
FROM temp_sip
END";
using (SqlConnection connection = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(str, connection))
{
cmd.Parameters.Add("@sipID", SqlDbType.Int).Value = sipID;
cmd.Parameters.Add("@frmID", SqlDbType.Int).Value = frmID;
//cmd.Parameters.AddWithValue("@frmID", frmID);
//cmd.Parameters.AddWithValue("@sipID", sipID);
connection.Open();
cmd.CommandType = CommandType.Text;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show($"Failed to create. Error message: {e.Message}");
}
}
}
}
I tried not passing any values and gave the values manually like;
v_emp(18846,201113))
And it created 2 temp tables successfully.
Did I miss something? What should I change? Thanks in advance.
UPDATE
This is the SQL Server Profiler output:
exec sp_executesql N'
BEGIN
if OBJECT_ID(''tempdb..#temp_sip1'') is not null
drop table #temp_sip1;
WITH temp_sip as(
select distinct ehID, ehSira, ehStkID, ehAdet, ehAdetN, ehTutar, ehIndirim, ehKDV, ehi1, ehi2, ehi3, ehi4, ehi5, ehiT6, ehDurum,
ehTutarKDV, ehBirim, ehSevkAdet, ehTutarDvz, ehSevkKontrol, ehNot, ehSipBag, ehAltStkID, ROW_NUMBER() OVER(PARTITION BY ehStkID ORDER BY ehAdet DESC) AS rank
from v_emp(@sipID, @frmID))
SELECT *
into #temp_sip1
FROM temp_sip
WHERE rank = 1
if OBJECT_ID(''tempdb..#temp_sip2'') is not null
drop table #temp_sip2;
WITH temp_sip as(
select distinct ehID, ROW_NUMBER() OVER(PARTITION BY ehID ORDER BY ehStkID DESC) ehSira, ehStkID, ehAdet, ehAdetN, ehTutar, ehIndirim, ehKDV, ehi1, ehi2, ehi3, ehi4, ehi5, ehiT6, ehDurum,
ehTutarKDV, ehBirim, ehSevkAdet, ehTutarDvz, ehSevkKontrol, ehNot, ehSipBag, ehAltStkID
from #temp_sip1)
SELECT *
into #temp_sip2
FROM temp_sip
END',N'@sipID int,@frmID int',@sipID=18846,@frmID=201113