Invalid Object name '##Temporary_table' - c#

I have stored procedure, which works fine if executed by SQL Server management studio. When Calling it from ASP.net MVC app it throws temporary table exception like Invalid object name '##temp_demographic_data_set'.
Any Clue, Why this error occurs when execute from C#.
Below is the stored procedure Code:
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_get_demographic_history_csv]
#_startdate datetime,
#_enddate datetime,
#_nccs varchar(56),
#_megacity varchar(56),
#_10lac varchar(56),
#_below10 varchar(56),
#_rural varchar(56),
#_state_megacity varchar(56) =NULL,
#_state_10lac varchar(56) =NULL,
#_state_below10 varchar(56) =NULL,
#_state_rural varchar(56) =NULL,
#_gender varchar(56),
#_agegroup varchar(56),
#limt int =NULL,
#off_set int =NULL,
#_Subscription_start datetime,
#_Subscription_end datetime,
#_demographic_field_id varchar(max),
#templateid int
AS
BEGIN
DECLARE #demographic_columns varchar(max);
DECLARE #temp_query nvarchar(max);
DECLARE #parameter_defination_list nvarchar(max);
DECLARE #parameter_list nvarchar(max);
-- Variables to check whether user is allowed to query on columns or not
DECLARE #is_nccs_exist varchar(20);
DECLARE #is_agegroup_exist varchar(20);
DECLARE #is_stategroup_exist int;
DECLARE #is_townclass_exist int;
DECLARE #is_gender_exist varchar(20);
DECLARE #demographic_view nvarchar(max);
DECLARE #demographic_report varchar(max);
DECLARE #record_count int;
-- DECLARE #tableid varchar(56);
SET XACT_ABORT ON
SET NOCOUNT ON
-- Set Defaults
SET #is_nccs_exist ='false';
SET #is_agegroup_exist ='false';
SET #is_stategroup_exist =0;
SET #is_townclass_exist =0;
SET #is_gender_exist ='false';
-- Get values from the template
SELECT
#is_gender_exist=max(CASE WHEN demofield.name='master_gender' THEN 'true' ELSE 'false' END),
#is_townclass_exist=max(CASE WHEN demofield.name='master_town_class' THEN 1 ELSE 0 END) ,
#is_stategroup_exist=max(CASE WHEN demofield.name='master_state_group' THEN 1 ELSE 0 END),
#is_agegroup_exist=max(CASE WHEN demofield.name='master_age_group' THEN 'true' ELSE 'false' END),
#is_nccs_exist=max(CASE WHEN demofield.name='master_nccs' THEN 'true' ELSE 'false' END)
FROM dbo.template_demographic_fields template
INNER JOIN demgraphic_fields demofield on template.field_id=demofield.id
WHERE demofield.is_inventory_field=1 and (#templateid=0 OR template_id=#templateid);
-- Update Variables
SET #is_nccs_exist =COALESCE(#is_nccs_exist,'false');
SET #is_agegroup_exist =COALESCE(#is_agegroup_exist,'false');
SET #is_stategroup_exist=COALESCE(#is_stategroup_exist,0);
SET #is_townclass_exist =COALESCE(#is_townclass_exist,0);
SET #is_gender_exist =COALESCE(#is_gender_exist,'false');
exec dbo.sp_split_string_into_rows #_demographic_field_id;
-- Get Demographic columns from table
select #demographic_columns=
(
COALESCE(#demographic_columns+ ',', '') +
CAST( (case when return_as is not null then name+' as '+ '['+return_as+']' else '['+name+']' end) AS VARCHAR(max))
)
from dbo.demgraphic_fields
where is_inventory_field=0 and ( #templateid=0 OR id in (select cast(split_data as int) from ##temp_convert));
set #demographic_columns=#demographic_columns+','+'state_group as state_group_code,town_class as town_class_code,
nccs_group as nccs_group_code,age_group as age_group_code, sex as gender,file_date,member_id';
select #demographic_report=
(
COALESCE(#demographic_report+ ',', '') +
CAST( (case when return_as is not null then '['+return_as+']' else '['+name+']' end) AS VARCHAR(max))
)
from dbo.demgraphic_fields
where is_inventory_field=0 and ( #templateid=0 OR id in (select cast(split_data as int) from ##temp_convert));
select #demographic_view=
(
COALESCE(#demographic_view+ ',', '') +
CAST( (case when return_as is not null then '['+return_as+'] VARCHAR(56),' else '['+name+'] VARCHAR(56),' end) AS VARCHAR(max))
)
from dbo.demgraphic_fields
where is_inventory_field=0 and ( #templateid=0 OR id in (select cast(split_data as int) from ##temp_convert));
SET #demographic_view='CREATE TABLE ##temp_demographic_data_set ('+(#demographic_view+'state_group_code VARCHAR(56), town_class_code VARCHAR(56),
nccs_group_code VARCHAR(56),age_group_code VARCHAR(56), gender VARCHAR(56),file_date datetime,member_id VARCHAR(56)')+');'
if object_id('tempdb..##temp_demographic_data_set') is not null drop table ##temp_demographic_data_set ;
execute sp_executesql #demographic_view;
-- drop temporary table if already exist & create temporary table
if object_id('tempdb..#temp_state_megacity') is not null drop table #temp_state_megacity ;
-- execute procedure to split comman seprated input value into rows
exec dbo.sp_split_string_into_rows #_state_megacity;
-- get comma separated to row converted value into temporary table.
select distinct _stategroup_code.*,_stategroup.is_exposed into #temp_state_megacity from _stategroup_code
INNER JOIN _stategroup on _stategroup_code.stategroup_id=_stategroup.id
where #templateid=0 OR
_stategroup_code.stategroup_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='STATE_GROUP' and (template_id=#templateid))
);
if object_id('tempdb..#temp_state_10lac') is not null drop table #temp_state_10lac ;
exec dbo.sp_split_string_into_rows #_state_10lac;
select distinct _stategroup_code.*,_stategroup.is_exposed into #temp_state_10lac from _stategroup_code
INNER JOIN _stategroup on _stategroup_code.stategroup_id=_stategroup.id
where #templateid=0 OR _stategroup_code.stategroup_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='STATE_GROUP' and (template_id=#templateid))
);
if object_id('tempdb..#temp_state_below10') is not null drop table #temp_state_below10 ;
exec dbo.sp_split_string_into_rows #_state_below10;
select distinct _stategroup_code.*,_stategroup.is_exposed into #temp_state_below10 from _stategroup_code
INNER JOIN _stategroup on _stategroup_code.stategroup_id=_stategroup.id
where #templateid=0 OR _stategroup_code.stategroup_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='STATE_GROUP' and (template_id=#templateid))
);
if object_id('tempdb..#temp_state_rural') is not null drop table #temp_state_rural ;
exec dbo.sp_split_string_into_rows #_state_rural;
select distinct _stategroup_code.*,_stategroup.is_exposed into #temp_state_rural
from _stategroup_code
INNER JOIN _stategroup on _stategroup_code.stategroup_id=_stategroup.id
where #templateid=0 OR _stategroup_code.stategroup_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='STATE_GROUP' and (template_id=#templateid))
);
if object_id('tempdb..#temp_nccs') is not null drop table #temp_nccs;
exec dbo.sp_split_string_into_rows #_nccs;
select distinct * into #temp_nccs from _nccs_code
where #templateid=0 OR _nccs_code.nccs_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='NCCS' and (template_id=#templateid))
);
if object_id('tempdb..#temp_gender') is not null drop table #temp_gender ;
exec dbo.sp_split_string_into_rows #_gender;
select distinct * into #temp_gender from ##temp_convert;
if object_id('tempdb..#temp_agegroup') is not null drop table #temp_agegroup ;
exec dbo.sp_split_string_into_rows #_agegroup;
select distinct * into #temp_agegroup from _agegroup_code
where #templateid=0 OR _agegroup_code.agegroup_id in
(
select split_data from ##temp_convert
WHERE split_data in (SELECT master_id from master_template where master_type='AGE_GROUP' and template_id =#templateid)
);
if object_id('tempdb..#temp_demographic_data') is not null drop table #temp_demographic_data ;
SET #parameter_defination_list= ' #temp_startdate datetime,
#temp_enddate datetime,
#temp_Subscription_start datetime,
#temp_Subscription_end datetime,
#temp_is_nccs_exist varchar(56),
#temp_is_agegroup_exist varchar(56),
#temp_is_gender_exist varchar(56)';
-- Loading Data To Temporary table for the filters provided
SET #temp_query=
'INSERT INTO ##temp_demographic_data_set SELECT '+#demographic_columns+'
FROM dbo.raw_demographic_history
where (file_date between cast(#temp_Subscription_start as datetime) and cast(#temp_Subscription_end as datetime)) and
(file_date between cast(#temp_startdate as datetime) and cast(#temp_enddate as datetime) )
and
(NOT #temp_is_nccs_exist=''true'' OR nccs_group in (select code from #temp_nccs) )and
(NOT #temp_is_gender_exist=''true'' OR sex in (select * from #temp_gender) )and
(NOT #temp_is_agegroup_exist=''true'' OR age_group in (select code from #temp_agegroup) );';
execute sp_executesql #temp_query ,#parameter_defination_list,
#temp_startdate=#_startdate ,
#temp_enddate=#_enddate,
#temp_Subscription_start=#_Subscription_start ,
#temp_Subscription_end=#_Subscription_end,
#temp_is_nccs_exist=#is_nccs_exist,
#temp_is_agegroup_exist=#is_agegroup_exist,
#temp_is_gender_exist=is_gender_exist;
-- Creating table with empty columns
SELECT * INTO #temp_demographic_data FROM ##temp_demographic_data_set WHERE state_group_code=0;
-- Create Indexes
CREATE INDEX IX_TEST_temp_demographic_data_1 ON #temp_demographic_data(nccs_group_code);
CREATE INDEX IX_TEST_temp_demographic_data_2 ON #temp_demographic_data(town_class_code);
CREATE INDEX IX_TEST_temp_demographic_data_3 ON #temp_demographic_data(age_group_code);
CREATE INDEX IX_TEST_temp_demographic_data_4 ON #temp_demographic_data(state_group_code);
CREATE INDEX IX_TEST_temp_demographic_data_5 ON #temp_demographic_data(member_id);
CREATE INDEX IX_TEST_file_date_6 ON #temp_demographic_data(file_date);
-- When All India IS True
IF (#_state_megacity is null AND #_state_10lac is null AND #_state_below10 is null AND #_state_rural is null)
BEGIN
INSERT INTO #temp_demographic_data SELECT * FROM ##temp_demographic_data_set;
-- SET Town class to empty
/*
UPDATE #temp_demographic_data
SET town_class_code=NULL
WHERE (state_group_code in (select code from #temp_state_megacity WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_10lac WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_below10 WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_rural WHERE is_exposed=0)) ;
*/
END
ELSE
BEGIN
-- WHEN All India is false and state,town columns exist in template
IF #is_stategroup_exist=1 and #is_townclass_exist=1
BEGIN
-- Update Town class to empty for states not exposed to user
INSERT INTO #temp_demographic_data
SELECT * FROM
(
SELECT * FROM ##temp_demographic_data_set
WHERE
(state_group_code in (select code from #temp_state_megacity WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_10lac WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_below10 WHERE is_exposed=0)) OR
(state_group_code in (select code from #temp_state_rural WHERE is_exposed=0))
UNION ALL
SELECT * FROM ##temp_demographic_data_set
WHERE
(town_class_code=#_megacity and state_group_code in (select code from #temp_state_megacity WHERE is_exposed=1)) OR
(town_class_code=#_10lac and state_group_code in (select code from #temp_state_10lac WHERE is_exposed=1)) OR
(town_class_code=#_below10 and state_group_code in (select code from #temp_state_below10 WHERE is_exposed=1)) OR
(town_class_code=#_rural and state_group_code in (select code from #temp_state_rural WHERE is_exposed=1))
)demographic_data;
/*UPDATE #temp_demographic_data
SET town_class_code=NULL
WHERE (state_group_code,town_class_code) in();
*/
END
-- When Only StateGroup Exists
IF #is_stategroup_exist=1 and #is_townclass_exist=0
BEGIN
INSERT INTO #temp_demographic_data
SELECT * FROM ##temp_demographic_data_set
WHERE
(state_group_code in (select code from #temp_state_megacity )) OR
(state_group_code in (select code from #temp_state_10lac )) OR
(state_group_code in (select code from #temp_state_below10)) OR
(state_group_code in (select code from #temp_state_rural)) ;
END
-- When Only Town class Exists
IF #is_stategroup_exist=0 and #is_townclass_exist=1
BEGIN
INSERT INTO #temp_demographic_data
SELECT * FROM ##temp_demographic_data_set;
END
-- When State and Town Both Not exists
IF #is_stategroup_exist=0 and #is_townclass_exist=0
BEGIN
INSERT INTO #temp_demographic_data
SELECT * FROM ##temp_demographic_data_set;
END
END
-- select #temp_query;
-- execute sp_executesql #temp_query;
if object_id('tempdb..##temp_report_data') is not null drop table ##temp_report_data ;
-- if object_id('tempdb..##temp_report_data1') is not null drop table ##temp_report_data1 ;
-- when input limit value is not null then
SET #temp_query='
SELECT *,ROW_NUMBER() OVER (ORDER BY file_date,member_id) as row_number INTO ##temp_report_data
FROM
(
SELECT DISTINCT file_date,member_id,'+#demographic_report+'
FROM
(
SELECT DISTINCT
coalesce(_nccs.name,'''') as master_nccs,
coalesce(_stategroup.name,'''') as master_state_group,
coalesce(CASE WHEN _stategroup_code.is_exposed=0 THEN '''' ELSE _townclass.name END,'''') as master_town_class,
coalesce(_agegroup.name,'''') as master_age_group,
coalesce(CASE WHEN filetered_data.gender=1 THEN ''MALE'' ELSE ''FEMALE'' END,'''')as master_gender,
-- cast(round(filetered_data.weight,2) as char(10)) as weight,filetered_data.household_id,
filetered_data.*
from(
select DISTINCT *
from #temp_demographic_data
)as filetered_data
left join #temp_nccs _nccs_code on filetered_data.nccs_group_code=_nccs_code.code
left join _nccs on _nccs_code.nccs_id=_nccs.id
left join _townclass on filetered_data.town_class_code=_townclass.code
left join #temp_agegroup _agegroup_code on filetered_data.age_group_code=_agegroup_code.code
left join _agegroup on _agegroup_code.agegroup_id=_agegroup.id
left join (
select * from #temp_state_megacity
union
select * from #temp_state_10lac
union
select * from #temp_state_below10
union
select * from #temp_state_rural
)_stategroup_code on filetered_data.state_group_code=_stategroup_code.code
left join _stategroup on _stategroup_code.stategroup_id=_stategroup.id
)report
) report_view';
execute sp_executesql #temp_query ;
CREATE INDEX IX_TEST_temp_temp_report_data ON ##temp_report_data(row_number);
SET #record_count=(SELECT max(row_number) FROM ##temp_report_data);
IF #limt is not null
begin
select *,#record_count as count FROM ##temp_report_data
where row_number between #off_set and #off_set+#limt;
end
-- when input limit value is null
else
begin
select *,#record_count as count FROM ##temp_report_data
END
-- Drop temporary tables
if object_id('tempdb..#temp_demographic_data') is not null drop table #temp_demographic_data ;
if object_id('tempdb..##temp_demographic_data_set') is not null drop table ##temp_demographic_data_set ;
if object_id('tempdb..#temp_agegroup') is not null drop table #temp_agegroup ;
if object_id('tempdb..#temp_gender') is not null drop table #temp_gender ;
if object_id('tempdb..#temp_nccs') is not null drop table #temp_nccs;
if object_id('tempdb..#temp_state_rural') is not null drop table #temp_state_rural ;
if object_id('tempdb..#temp_state_below10') is not null drop table #temp_state_below10 ;
if object_id('tempdb..#temp_state_10lac') is not null drop table #temp_state_10lac ;
if object_id('tempdb..#temp_state_megacity') is not null drop table #temp_state_megacity ;
END
C# Code :
SqlParameter[] mySqlParam = new SqlParameter[19];
mySqlParam[0] = new SqlParameter("_startdate", startDate);
mySqlParam[1] = new SqlParameter("_enddate", endOfDay);
mySqlParam[2] = new SqlParameter("_nccs", nccs == "" ? null : nccs);
mySqlParam[3] = new SqlParameter("_megacity", Convert.ToInt32(ConfigurationManager.AppSettings["megacities"]));
mySqlParam[4] = new SqlParameter("_10lac", Convert.ToInt32(ConfigurationManager.AppSettings["tento75L"]));
mySqlParam[5] = new SqlParameter("_below10", Convert.ToInt32(ConfigurationManager.AppSettings["urban"]));
mySqlParam[6] = new SqlParameter("_rural", Convert.ToInt32(ConfigurationManager.AppSettings["rural"]));
mySqlParam[7] = new SqlParameter("_state_megacity", megaCities == "" ? null : megaCities);
mySqlParam[8] = new SqlParameter("_state_10lac", tenTo75Lac == "" ? null : tenTo75Lac);
mySqlParam[9] = new SqlParameter("_state_below10", urban == "" ? null : urban);
mySqlParam[10] = new SqlParameter("_state_rural", rural == "" ? null : rural);
string gender = null;
if (male == true && female == true)
{
gender = ConfigurationManager.AppSettings["male"] + "," + ConfigurationManager.AppSettings["female"];
}
else if (male == true)
{
gender = ConfigurationManager.AppSettings["male"];
}
else if (female == true)
{
gender = ConfigurationManager.AppSettings["female"];
}
mySqlParam[11] = new SqlParameter("_gender", gender);
mySqlParam[12] = new SqlParameter("_agegroup", ageGroup == "" ? null : ageGroup);
mySqlParam[13] = new SqlParameter("off_set", offSet);
mySqlParam[14] = new SqlParameter("limt", limit);
mySqlParam[15] = new SqlParameter("_Subscription_start", subscription_start);
mySqlParam[16] = new SqlParameter("_Subscription_end", endOfDaySubscription);
mySqlParam[17] = new SqlParameter("_demographic_field_id ", demographicFields);
mySqlParam[18] = new SqlParameter("templateid ", templateId);
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(GlobalConstants.ConnString, CommandType.StoredProcedure, ConfigurationManager.AppSettings["usp_get_demographic_history_csv"].ToString(), mySqlParam);
return ds;
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
//create & open an SqlConnection, and dispose of it after we are done.
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
//call the overload that takes a connection in place of the connection string
return ExecuteDataset(cn, commandType, commandText, commandParameters);
}
}

Is it possible that, in production, there're instances where the script returns no rows?
select #demographic_report= {...}
from dbo.demgraphic_fields
where is_inventory_field=0 and ( #templateid=0 OR id in (select cast(split_data as int) from ##temp_convert));
If this is the case, #demographic_report remains null, 'any string' + null is null, sp_executesql is executed against a null string that does nothing, but the table is not created and this causes your error.

Related

Query return result in SSMS but not in C#

My database developer gave me a SQL query and it runs successfully in SSMS.
USE testdb
DECLARE #Pipeline TABLE
(
pipeline VARCHAR(4000),
unitcode VARCHAR(4000),
designareanumber VARCHAR(4000),
nameofnote VARCHAR(4000)
)
INSERT INTO #Pipeline
SELECT pipeline,
unitcode,
designareanumber,
nameofnote
FROM (SELECT pp.oid AS OID,
nmpp.itemname AS ItemName,
nmpl.itemname AS Pipeline,
tn.trainnumber AS TrainNumber,
uc.unitcode AS UnitCode,
FROM jrtepipepart pp
JOIN jnameditem nmpp
ON pp.oid = nmpp.oid
JOIN xcontainsnote xcn
ON pp.oid = xcn.oidorigin
WHERE gn.text <> ''
AND ( nmpps.itemname = 'Piping_New'
OR nmpps.itemname = 'Piping_Modified/Tie_In' )
--where gn.Text like '%000002A_TP08' AND (nmpps.ItemName = 'Piping_New' OR nmpps.ItemName = 'Piping_Modified/Tie_In')
UNION ALL
SELECT hs.oid AS OID,
nmhs.itemname AS ItemName,
nmpl.itemname AS Pipeline,
tn.trainnumber AS TrainNumber,
uc.unitcode AS UnitCode,
FROM jhgrsupport hs
JOIN jnameditem nmhs
ON hs.oid = nmhs.oid
WHERE gn.text <> ''
AND ( nmpps.itemname = 'Piping_New'
OR nmpps.itemname = 'Piping_Modified/Tie_In' ))A
SELECT pipeline,
unitcode,
designareanumber,
( Stuff((SELECT Cast('; ' + nameofnote AS VARCHAR(max))
FROM #Pipeline p2
WHERE ( p2.pipeline = p1.pipeline
AND p2.unitcode = p1.unitcode
AND p2.designareanumber = p1.designareanumber
AND nameofnote NOT IN ( 'Note 1', '' ) )
FOR xml path ('')), 1, 2, '') ) AS NameOfNote
FROM #Pipeline p1
WHERE nameofnote NOT IN ( 'Note 1', '' )
GROUP BY pipeline,
unitcode,
designareanumber
When I run above query in OleDbDataAdapter it return 0 rows. I have tried adding SET NOCOUNT ON at start of the query but not working. I have increased set-timeout property.
Removed USE testdb, added SET NOCOUNT ON and added database name before table names resolved this issue.

Timeout expired. The timeout period elapsed prior to completion of the operation

I an a stored procedure which selects files with pagination criteria
In this problem, when run this stored procedure, get an exception
Timeout expired. The timeout period elapsed prior to completion of the operation
How to works again without above exception?
My researches and tries:
I compared same db on two database servers(prod and test). Test server can work and prod one can not.
I changed connecion string to add "connect timeout=30000" (5 mins)
I also added CommandTimeOut=30000 at file list method.
Additional information: Prod's db server and IIS server placed different server. I searced some articles and because of the slow connection or heavier traffic on db server. But I encountered this error at first time on today.
My stored procedure located below
ALTER PROCEDURE [dbo].[inwsDosyaListesiSirali]
#SiteId INT,
#KullaniciId int,
#SubeIp varchar(max),
#DepartmanId int,
#KategoriKod VARCHAR(200)= null,
#Baslik VARCHAR(100) = null,
#IlkTarih DATETIME=null,
#SonTarih DATETIME=null,
#Icerik varchar(max) = null,
#PageNumber INT=1,
#PageSize INT=10,
#SortColumn varchar(100)=null,
#SortOrder BIT=null
AS
BEGIN
DECLARE #KategoriKodListe TABLE(KategoriKod VARCHAR(20) primary key);
INSERT INTO #KategoriKodListe
SELECT Item FROM dbo.SplitString(#KategoriKod,',')
declare #SubeId int,
#DepartmanTurId int ,
#SubeKategoriKod varchar(100)
SELECT #DepartmanTurId=[DepartmanTurId] FROM [Departman]
where [SiteId]=#SiteId and [Id] = #DepartmanId
select #SubeId=ks.SubeId, #SubeKategoriKod = ksk.Kod from [dbo].[KurumsalSube] ks
inner join [dbo].[KurumsalSubeKategori] ksk on ks.KategoriId = ksk.KategoriId
where SiteId=#SiteId and SubeIp like '%'+#SubeIp+'%'
;With EMP AS (
SELECT
r.RaporId
,r.HistoryId
,r.Baslik
,r.DosyaAd
,r.RaporAktifTarih
,r.RaporGecerlilikTarih
,r.RaporTarih
,r.KategoriId
,h.KayitTarih
,r.ParentRaporId
,kat.Ad [KategoriAd]
,kat.Kod [KategoriKod]
,kat.Sira
,T.DosyaTurId
,T.Ad AS DosyaTurAd
--,T.Uzanti AS DosyaUzanti
,T.iconName
--,(ROW_NUMBER() OVER (PARTITION BY r.[KategoriId] ORDER BY r.[RaporTarih] desc)) AS number
,s.SistemDosyaId
,s.DosyaAdi as SistemDosyaAd
FROM Dosya r
INNER JOIN DosyaKategori kat ON kat.KategoriId=r.KategoriId
INNER JOIN DosyaHistory h ON h.Id=r.HistoryId
LEFT JOIN DosyaTur T ON T.DosyaTurId=r.DosyaTurId
LEFT JOIN DosyaIcerik di ON r.SistemDosyaId = di.SistemDosyaId
--Yetki kontrol kısmı
left join [dbo].[DosyaYetki] dy on r.DosyaYetkiId = dy.DosyaYetkiId
LEFT JOIN SistemDosyalari s ON s.SistemDosyaId=r.SistemDosyaId
WHERE kat.SiteId=#SiteId AND r.IsOnay=1
AND (isnull(#KategoriKod,'') = '' or exists(select 1 from #KategoriKodListe k where k.KategoriKod=kat.Kod) )
AND ((NULLIF(r.RaporGecerlilikTarih,'') IS NULL OR (r.RaporGecerlilikTarih >= GETDATE())))
AND ((NULLIF(r.RaporAktifTarih,'') IS NULL OR (r.RaporAktifTarih <= GETDATE())))
-- AND ((NULLIF(#Baslik,'') IS NULL OR (r.Baslik like '%'+#Baslik+'%' ) OR NULLIF(r.ParentRaporId,'') IS NOT NULL))
--AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,r.RaporTarih)))))
--AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date, DATEADD(day,0,r.RaporTarih)))))
--AND ((NULLIF(#Icerik,'') IS NULL OR (di.Icerik like '%'+#Icerik+'%') OR NULLIF(r.ParentRaporId,'') IS NOT NULL))
--Yetki kontrol kısmı
and (
dy.DosyaYetkiId is null or
(
dy.SiteId=#SiteId and
(
r.DosyaYetkiId is null or r.[HerkeseGosterilsin]=1 or -- herkese açık demek oluyor
(#DepartmanTurId=1 and #SubeKategoriKod='INGENELMUDURLUK' ) or -- Kategori Kod : INGENELMUDURLUK ve yönetim departmanında ise tüm dosyaları görebilsin
(
(
-- Isnull(dys.SubeId,'')='' or
-- dys.SubeId=#SubeId
exists(select 1 from [dbo].[DosyaYetkiSube] dys where dys.SubeId=#SubeId )
or not exists(select 1 from [dbo].[DosyaYetkiSube] dys where dys.DosyaYetkiId=r.DosyaYetkiId )
)and
(
#DepartmanTurId=1 -- #DepartmanTurId=1 ise şubenin yönetici olarak o şubede ki tüm dosyaları görebilir
-- or Isnull(dyd.DepartmanId,'')=''
-- dyd.DepartmanId=#DepartmanId
or exists(select 1 from [dbo].[DosyaYetkiDepartman] dyd where dyd.DepartmanId = #DepartmanId)
or not exists(select 1 from [dbo].[DosyaYetkiDepartman] dyd where dyd.DosyaYetkiId = r.DosyaYetkiId )
)and
(
#DepartmanTurId=1 -- #DepartmanTurId=1 ise şubenin yönetici olarak o şubede ki tüm dosyaları görebilir
-- or Isnull(dyp.PersonelId,'')=''
-- dyp.PersonelId=#KullaniciId
or exists(select 1 from [dbo].[DosyaYetkiPersonel] dyp where dyp.PersonelId=#KullaniciId )
or not exists(select 1 from [dbo].[DosyaYetkiPersonel] dyp where dyp.DosyaYetkiId = r.DosyaYetkiId )
)
)
)
)
)
),
cte AS
(
SELECT CAST(ROW_NUMBER() OVER(order by
CASE WHEN (RTRIM(LTRIM(#SortColumn)) IS NULL)
THEN KayitTarih END DESC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=1)
THEN Baslik END ASC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=0)
THEN Baslik END DESC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=1)
THEN KayitTarih END ASC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=0)
THEN KayitTarih END DESC
) AS REAL) AS NUMBER, 1 AS Indent, Parent.* FROM EMP Parent WHERE Parent.ParentRaporId IS NULL
UNION ALL
SELECT c.NUMBER + (CAST(ROW_NUMBER() OVER(ORDER BY
CASE WHEN (RTRIM(LTRIM(#SortColumn)) IS NULL)
THEN child.KayitTarih END DESC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=1)
THEN child.Baslik END ASC,
CASE WHEN (#SortColumn = 'Baslik' AND #SortOrder=0)
THEN child.Baslik END DESC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=1)
THEN child.KayitTarih END ASC,
CASE WHEN (#SortColumn = 'Tarih' AND #SortOrder=0)
THEN child.KayitTarih END DESC
) AS REAL)/POWER(10, c.Indent) ) AS NUMBER, c.Indent + 1 AS Indent, child.* FROM EMP
child INNER JOIN cte c ON child.ParentRaporId= c.RaporId
),Count_CTE AS (
SELECT COUNT(*) AS [TotalCount]
FROM cte
WHERE (NULLIF(#Baslik,'') IS NULL OR (cte.Baslik like '%'+#Baslik+'%' ))
AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date,
DATEADD(day,0,cte.RaporTarih)))))
AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date,
DATEADD(day,0,cte.RaporTarih)))))
) SELECT * FROM cte, Count_CTE
WHERE (NULLIF(#Baslik,'') IS NULL OR (cte.Baslik like '%'+#Baslik+'%' ))
AND ((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
AND ((NULLIF(#SonTarih,'') IS NULL OR (#SonTarih>=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
ORDER BY cte.NUMBER
OFFSET (#PageNumber-1)*#PageSize ROWS FETCH NEXT #PageSize ROWS ONLY
END
Add OPTION RECOMPILE and transform the non-SARGable where clauses. see http://sommarskog.se/dyn-search.html
eg
((NULLIF(#IlkTarih,'') IS NULL OR (#IlkTarih<=CONVERT(date, DATEADD(day,0,cte.RaporTarih)))))
should be
#IlkTarih is null or cast(#IlkTarih as date)<=cte.RaporTarih
I resolved this issue with adjust memory on SQL Server management studio because of low memory of db server.
If record is high, then query execution can take a long time.

SQL Server: return the result of a select as a result of stored procedure execution

I have a stored procedure that is called from C#:
CREATE PROCEDURE [MySP]
#ID int,
#Exists bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Exists = 0
SELECT TOP 1 ID
FROM MyTable
WHERE ID = #ID
IF ##ROWCOUNT = 0
BEGIN
SELECT b.*
FROM AnotherTable b
INNER JOIN AnotherTable2 c ON b.ID = c.ID
WHERE b.ID = #ID
END
ELSE
BEGIN
SET #Exists = 1
SELECT TOP 0 NULL
END
END
IF #ID does not exist in table MyTable, then I return the SELECT b.*, otherwise if #ID exists in the table, then I return no rows
The problem is that when #ID exists in the table, the stored procedure returns two tables as a result to C#, the one from SELECT TOP 1 and the one from SELECT b.* and I only want to return SELECT b.* so how can I do this?
Just replace all the logic with:
SELECT b.*
From AnotherTable b INNER JOIN
AnotherTable2 c
ON b.ID = c.ID
WHERE b.ID = #ID AND
NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = #ID);
And, if you don't want duplicates, you might as well do:
SELECT b.*
From AnotherTable b
WHERE b.ID = #ID AND
EXISTS (SELECT 1 FROM AnotherTable2 c WHERE b.ID = c.ID) AND
NOT EXISTS (SELECT 1 FROM MyTable WHERE ID = #ID);
Then, learn about table valued functions. If you want to return a table, then the best approach -- if it is feasible -- is a function, not a stored procedure.
(Functions are more limited in their functionality, so this is not always possible.)
Use exists for this:
CREATE PROCEDURE [MySP]
#ID int,
#Exists bit OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #Exists = 0
IF EXISTS(SELECT TOP 1 ID FROM MyTable WHERE ID = #ID)
BEGIN
SELECT b.*
From AnotherTable b
INNER JOIN AnotherTable2 c on b.ID = c.ID
Where b.ID = #ID
END
ELSE
BEGIN
SET #Exists = 1
SELECT TOP 0 NULL
END
END
The second result that you are getting is from the statement select top 0 null

Is it possible to transpose a table's entries and store it into a temp table in SQL Server?

I would like to transpose the data from my table and do some plottings into powerBI.
Here is how I feel up my database from my application:
using (SqlCommand cmd = connect.CreateCommand())
{
cmd.CommandText = #"INSERT INTO PoD_NewPriceList_Data
(ID, Product_Barcode, Product_Name,
Store_Price, Internet_Price, InsertDate)
VALUES (#ID, #Product_Barcode, #Product_Name,
#Store_Price, #Internet_Price, #InsertDate)";
cmd.Parameters.Add("Product_Barcode", SqlDbType.NVarChar).Value = barcode;
cmd.Parameters.Add("Product_Name", SqlDbType.NVarChar).Value = PriceList.name;
cmd.Parameters.Add("Store_Price", SqlDbType.Float).Value = Convert.ToDouble(storePrice, CultureInfo.InvariantCulture);
cmd.Parameters.Add("Internet_Price", SqlDbType.Float).Value = Convert.ToDouble(PriceList.price, CultureInfo.InvariantCulture);
cmd.Parameters.Add("InsertDate", SqlDbType.DateTime).Value = InsertDate.AddDays(2);
cmd.Parameters.Add("ID", SqlDbType.Int).Value = barcode.GetHashCode();
result = result && (cmd.ExecuteNonQuery() > 0);
}
And in SQL Server Management Studio here is how my table looks like:
SELECT
[ID], [Product_Barcode], [Product_Name],
[Store_Price], [Internet_Price], [InsertDate]
FROM
[dbo].[PoD_NewPriceList_Data]
and I get the following output:
The main issue is when trying to create the plots as requested in PowerBI I need my data to look as follows:
F5321
Product_Name Sony Xperia...
Store_Price 399
Internet_Price 327.51
InsertDate 2017.04.27
Any help would be well appreciated.
Check and modify this SQL script. I use #t table variable, replace it with your table name [PoD_NewPriceList_Data].
DECLARE #t TABLE (
id int,
product_barcode varchar(max),
product_name varchar(max),
store_price int,
internet_price decimal,
insert_date date
)
INSERT INTO #t VALUES (1,'F5321', 'Sony Xperia', 399, 255.1, '2017-04-25')
INSERT INTO #t VALUES (2,'F5833', 'Sony Xperia XZ', 458, 398.2, '2017-04-26')
INSERT INTO #t VALUES (3,'F5121', 'Sony Xperia XA Rose', 161, 155.6, '2017-04-27')
IF OBJECT_ID ('tempdb..#Unpivoted') IS NOT NULL
DROP TABLE #Unpivoted
IF OBJECT_ID ('tempdb..#Transposed') IS NOT NULL
DROP TABLE #Transposed
/* Unpivot table to get rows instead of columns */
SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT 0)) as rn
INTO #Unpivoted
FROM (SELECT product_barcode, product_name,
CAST(store_price as varchar(max)) store_price,
CAST(internet_price as varchar(max)) internet_price,
CAST(insert_date as varchar(max)) as insert_date
FROM #t) src
UNPIVOT (
value FOR field IN (
product_barcode, product_name, store_price, internet_price, insert_date
)
) unpiv
CREATE TABLE #Transposed
(Field varchar(50) PRIMARY KEY NOT NULL )
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = STUFF((
SELECT 'ALTER TABLE #Transposed ADD item' +
RIGHT('000' + CAST(sv.number AS VARCHAR(3)), 3) + ' varchar(max) '
FROM [master].dbo.spt_values sv
WHERE sv.[type] = 'p'
AND sv.number BETWEEN 1 AND (SELECT COUNT(*) FROM #t)
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')
Exec(#SQL) /* Dynamically create columns */
INSERT INTO #Transposed (Field) SELECT DISTINCT Field FROM #Unpivoted
/*populate field names*/
DECLARE #fieldCount int = (SELECT COUNT(*) FROM #Transposed)
/* using rn to filter proper record from transposed table */
SELECT #SQL = STUFF((
SELECT '
UPDATE #Transposed SET item' + RIGHT('000' + CAST(sv.number AS VARCHAR(3)), 3)
+ ' = up.value FROM #Transposed t CROSS APPLY
( SELECT TOP 1 u.value FROM #unpivoted u WHERE u.field = t.field AND u.rn > '
+ CAST((sv.number-1)*#fieldCount AS VARCHAR(10)) + ' ORDER BY rn) up '
FROM [master].dbo.spt_values sv
WHERE sv.[type] = 'p'
AND sv.number BETWEEN 1 AND (SELECT COUNT(*) FROM #t)
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')
Exec(#SQL) /*Dynamically fill in values */
SELECT t.* FROM #Transposed t
OUTER APPLY (SELECT TOP 1 rn FROM #Unpivoted u WHERE u.field=t.field) up
ORDER BY up.rn ASC /* add a link to Unpivoted to fix the item order */
DROP TABLE #Unpivoted
DROP TABLE #Transposed
It does what you need in several steps
converts columns to rows with UNPIVOT. Watch that you have to CAST all the values to the exactly same type. Adds a row number to filter the rows in step 3.
creates a temp table with dynamic number of columns corresponding to the number of rows
fills in the columns names into rows into the dynamically created table
fills in values into the dynamically created table
Credits to this answer and this answer.
Of course the number of columns is limited here, so if you try to convert many rows into columns, you get:
Cannot create a row of size 8066 which is greater than the allowable
maximum row size of 8060.

aggregation result from SQL view to gridview

I have this View from multi tables
account_name.......bonus..........value
customer1............A............14000
customer1............B............500
customer1............C............14500
customer2............A............20000
customer2............B............200
customer2............C............20200
http://im33.gulfup.com/Nt0mM.png
how can i retrieval this view and show it on GridView this View using LINQ
...................A.........B..........C
customer1.......14000.......500.......14500
customer2.......20000.......200.......20200
SELECT account_name,
SUM(CASE WHEN bonus = 'A' THEN value ELSE 0 END) AS A,
SUM(CASE WHEN bonus = 'B' THEN value ELSE 0 END) AS B,
SUM(CASE WHEN bonus = 'C' THEN value ELSE 0 END) AS C
FROM YouView
GROUP BY account_name
I solved my problem using Pivots with dynamic as realnumber3012 recommend...
the demonstrate of the table and the result on this link
DECLARE #cols NVARCHAR(2000)
SELECT #cols = COALESCE(#cols + ',[' + bounse_name+ ']','[' + bounse_name + ']')
FROM dbo.tbl_bounse
DECLARE #query NVARCHAR(4000)
SET #query = N'SELECT account_name , '+ #cols +'
FROM
(SELECT tbl_account.account_name, tbl_account.account_career,
tbl_bounse.bounse_name, tbl_detail.detail_value
FROM tbl_account INNER JOIN
tbl_detail ON tbl_account.account_id = tbl_detail.detail_accound_id
INNER JOIN
tbl_bounse ON tbl_detail.detail_bounce_id = tbl_bounse.bounse_id
) p
PIVOT
(
MAX([detail_value])
FOR bounse_name IN
( '+
#cols +' )
) AS pvt;'
EXECUTE(#query)

Categories

Resources