I understand I cant use [USE] statement within a sproc, however I need to query across several databases, this works great stand alone, how can I adapt this query to run across specified databases.
Would I have to Union all and specify each database?
Any Help is greatly appreciated
/* Intalytics section for TB*/
BEGIN
DECLARE #STARTDATE AS DATE = '2022-01-01'
,#ENDDATE AS DATE = '2022-02-28';
SET NOCOUNT ON;
IF OBJECT_ID(N'tempdb.dbo.#TB') IS NOT NULL
DROP TABLE #TB;
DECLARE #intcount INT
DECLARE #DATABASENAME NVARCHAR(25)
SET #intcount = 1
CREATE TABLE #TB (
Current_Database VARCHAR(50)
,Acct VARCHAR(50)
,AcctName NVARCHAR(100)
,[Month] DATETIME
,Oppening_Balance NUMERIC(18, 2)
,[Debit] NUMERIC(18, 2)
,[Credit] NUMERIC(18, 2)
,[Balance] NUMERIC(18, 2)
,[CBalance] NUMERIC(18, 2)
)
CREATE CLUSTERED INDEX ix_tempCIcOMPANY ON #TB (Acct)
WHILE (#intcount <= 23)
BEGIN
IF #intcount = 1
BEGIN
SET #DATABASENAME = 'KSS_INC'
USE [KSS_INC]
END
IF #intcount = 2
BEGIN
SET #DATABASENAME = 'KSS_LTD'
USE [KSS_LTD]
END
IF #intcount = 3
BEGIN
SET #DATABASENAME = 'MPSI_US'
USE [MPSI_US]
END
IF #intcount = 4
BEGIN
SET #DATABASENAME = 'KENTGRPLTD'
USE [KENTGRPLTD]
END
IF #intcount = 5
BEGIN
SET #DATABASENAME = 'KSS_INDIA'
USE [KSS_INDIA]
END
IF #intcount = 6
BEGIN
SET #DATABASENAME = 'KSS_Canada'
USE [KSS_Canada]
END
IF #intcount = 7
BEGIN
SET #DATABASENAME = 'KSS_AUS'
USE [KSS_AUS]
END
IF #intcount = 8
BEGIN
SET #DATABASENAME = 'MPS_INDIA'
USE [MPS_INDIA]
END
IF #intcount = 9
BEGIN
SET #DATABASENAME = 'MPSI_SAF'
USE [MPSI_SAF]
END
IF #intcount = 10
BEGIN
SET #DATABASENAME = 'MPSI_CAN'
USE [MPSI_CAN]
END
IF #intcount = 11
BEGIN
SET #DATABASENAME = 'MPSI_JAP'
USE [MPSI_JAP]
END
IF #intcount = 12
BEGIN
SET #DATABASENAME = 'MPSI_UK'
USE [MPSI_UK]
END
IF #intcount = 13
BEGIN
SET #DATABASENAME = 'MPSI_CHI'
USE [MPSI_CHI]
END
IF #intcount = 14
BEGIN
SET #DATABASENAME = 'KAL_LTD'
USE [KAL_LTD]
END
IF #intcount = 15
BEGIN
SET #DATABASENAME = 'TRADE_AREA_SYSTEMS'
USE [TRADE_AREA_SYSTEMS]
END
IF #intcount = 16
BEGIN
SET #DATABASENAME = 'INTALYTICS'
USE [INTALYTICS]
END
IF #intcount = 17
BEGIN
SET #DATABASENAME = 'KSSL_LTD'
USE [KSSL_LTD]
END
IF #intcount = 18
BEGIN
SET #DATABASENAME = 'MPSI'
USE [MPSI]
END
IF #intcount = 19
BEGIN
SET #DATABASENAME = 'MPSI_INT'
USE [MPSI_INT]
END
IF #intcount = 20
BEGIN
SET #DATABASENAME = 'MPSI_KOR'
USE [MPSI_KOR]
END
IF #intcount = 21
BEGIN
SET #DATABASENAME = 'NEW_SIS_SA'
USE [NEW_SIS_SA]
END
IF #intcount = 22
BEGIN
SET #DATABASENAME = 'MPSICHI_INC'
USE [MPSICHI_INC]
END
IF #intcount = 23 -- to stop loop after last database
BEGIN
BREAK
END
INSERT INTO #TB
SELECT #DATABASENAME
,T1.Account
,T2.AcctName
,CONCAT (
DATENAME(MONTH, T1.RefDate)
,' '
,YEAR(T1.REFDATE)
) AS [Month]
,Isnull((
SELECT SUM(T3.Debit - T3.Credit)
FROM dbo.OJDT T2
INNER JOIN dbo.JDT1 T3 ON T2.TransId = T3.TransId
WHERE DateDiff(dd, T2.RefDate, #StartDate) > 0
AND T3.Account LIKE T1.Account
GROUP BY T3.Account
), 0) 'Opening balance'
,SUM(T1.Debit) 'Debit'
,SUM(T1.Credit) 'Credit'
,SUM(T1.Debit - T1.Credit) AS 'Balance'
,Isnull((
SELECT SUM(T3.Debit - T3.Credit)
FROM dbo.OJDT T2
INNER JOIN dbo.JDT1 T3 ON T2.TransId = T3.TransId
WHERE DateDiff(dd, T2.RefDate, #StartDate) > 0
AND T3.Account LIKE T1.Account
GROUP BY T3.Account
), 0) + SUM(T1.Debit - T1.Credit) AS 'CBalance'
--- CB
FROM OJDT T0
INNER JOIN JDT1 T1 ON T0.TransId = T1.TransId
LEFT JOIN dbo.OACT T2 ON T2.AcctCode = T1.Account /*added to bring through */
WHERE T0.RefDate BETWEEN #StartDate
AND #EndDate
GROUP BY T1.Account
,T2.AcctName
,CONCAT (
DATENAME(MONTH, T1.RefDate)
,' '
,YEAR(T1.REFDATE)
)
,LEFT(DATENAME(MONTH, t1.RefDate), 3) + ' ' + RIGHT('00' + CAST(YEAR(t1.RefDate) AS VARCHAR), 2)
HAVING SUM(T1.Debit - T1.Credit) != 0
SET #intcount = #intcount + 1
END
SELECT *
FROM #TB AS t
END
DECLARE #SQL nvarchar
SET #SQL =''
WHILE (#intcount <= 23)
BEGIN
IF #intcount = 1
BEGIN
SET #DATABASENAME = 'KSS_INC'
USE [KSS_INC]
END
IF #intcount = 2
BEGIN
SET #DATABASENAME = 'KSS_LTD'
USE [KSS_LTD]
END
IF #intcount = 3
BEGIN
SET #DATABASENAME = 'MPSI_US'
USE [MPSI_US]
END
IF #intcount = 4
BEGIN
SET #DATABASENAME = 'KENTGRPLTD'
USE [KENTGRPLTD]
END
IF #intcount = 5
BEGIN
SET #DATABASENAME = 'KSS_INDIA'
USE [KSS_INDIA]
END
IF #intcount = 6
BEGIN
SET #DATABASENAME = 'KSS_Canada'
USE [KSS_Canada]
END
IF #intcount = 7
BEGIN
SET #DATABASENAME = 'KSS_AUS'
USE [KSS_AUS]
END
IF #intcount = 8
BEGIN
SET #DATABASENAME = 'MPS_INDIA'
USE [MPS_INDIA]
END
IF #intcount = 9
BEGIN
SET #DATABASENAME = 'MPSI_SAF'
USE [MPSI_SAF]
END
IF #intcount = 10
BEGIN
SET #DATABASENAME = 'MPSI_CAN'
USE [MPSI_CAN]
END
IF #intcount = 11
BEGIN
SET #DATABASENAME = 'MPSI_JAP'
USE [MPSI_JAP]
END
IF #intcount = 12
BEGIN
SET #DATABASENAME = 'MPSI_UK'
USE [MPSI_UK]
END
IF #intcount = 13
BEGIN
SET #DATABASENAME = 'MPSI_CHI'
USE [MPSI_CHI]
END
IF #intcount = 14
BEGIN
SET #DATABASENAME = 'KAL_LTD'
USE [KAL_LTD]
END
IF #intcount = 15
BEGIN
SET #DATABASENAME = 'TRADE_AREA_SYSTEMS'
USE [TRADE_AREA_SYSTEMS]
END
IF #intcount = 16
BEGIN
SET #DATABASENAME = 'INTALYTICS'
USE [INTALYTICS]
END
IF #intcount = 17
BEGIN
SET #DATABASENAME = 'KSSL_LTD'
USE [KSSL_LTD]
END
IF #intcount = 18
BEGIN
SET #DATABASENAME = 'MPSI'
USE [MPSI]
END
IF #intcount = 19
BEGIN
SET #DATABASENAME = 'MPSI_INT'
USE [MPSI_INT]
END
IF #intcount = 20
BEGIN
SET #DATABASENAME = 'MPSI_KOR'
USE [MPSI_KOR]
END
IF #intcount = 21
BEGIN
SET #DATABASENAME = 'NEW_SIS_SA'
USE [NEW_SIS_SA]
END
IF #intcount = 22
BEGIN
SET #DATABASENAME = 'MPSICHI_INC'
USE [MPSICHI_INC]
END
IF #intcount = 23 -- to stop loop after last database
BEGIN
BREAK
END
SET #SQL =' INSERT INTO #TB
SELECT' + #DATABASENAME +'
,T1.Account
,T2.AcctName
,CONCAT (
DATENAME(MONTH, T1.RefDate)
,'' ''
,YEAR(T1.REFDATE)
) AS [Month]
,Isnull((
SELECT SUM(T3.Debit - T3.Credit)
FROM '+#DATABASENAME+'.dbo.OJDT T2
INNER JOIN '+#DATABASENAME+'.dbo.JDT1 T3 ON T2.TransId = T3.TransId
WHERE DateDiff(dd, T2.RefDate, '+#StartDate+') > 0
AND T3.Account LIKE T1.Account
GROUP BY T3.Account
), 0) ''Opening balance''
,SUM(T1.Debit) ''Debit''
,SUM(T1.Credit) ''Credit''
,SUM(T1.Debit - T1.Credit) AS ''Balance''
,Isnull((
SELECT SUM(T3.Debit - T3.Credit)
FROM '+#DATABASENAME+'.dbo.OJDT T2
INNER JOIN '+#DATABASENAME+'.dbo.JDT1 T3 ON T2.TransId = T3.TransId
WHERE DateDiff(dd, T2.RefDate, '+#StartDate+') > 0
AND T3.Account LIKE T1.Account
GROUP BY T3.Account
), 0) + SUM(T1.Debit - T1.Credit) AS ''CBalance''
--- CB
FROM '+#DATABASENAME+'..OJDT T0
INNER JOIN '+#DATABASENAME+'..JDT1 T1 ON T0.TransId = T1.TransId
LEFT JOIN '+#DATABASENAME+'.dbo.OACT T2 ON T2.AcctCode = T1.Account
WHERE T0.RefDate BETWEEN '+#StartDate+'
AND '+#EndDate+'
GROUP BY T1.Account
,T2.AcctName
,CONCAT (
DATENAME(MONTH, T1.RefDate)
,'' ''
,YEAR(T1.REFDATE)
)
,LEFT(DATENAME(MONTH, t1.RefDate), 3) + '' '' + RIGHT(''00'' + CAST(YEAR(t1.RefDate) AS VARCHAR), 2)
HAVING SUM(T1.Debit - T1.Credit) != 0
SET '+#intcount+' = '+#intcount+' + 1
END
SELECT *
FROM '+#DATABASENAME+'..#TB AS t'
exec(#SQL)
Related
I have a SQL Server job defined as follows but it shows error while executing. Please help sort out the problem
-- First clear out the destination table fast and easy without
TRUNCATE TABLE [etimetracklite1].[dbo].[devicelogs];
-- Create table
DECLARE #tablename AS nvarchar(14);
DECLARE #yearnam AS nvarchar(4);
DECLARE #tabnam AS nvarchar(18);
IF MONTH(GETDATE()) = 1
BEGIN
SET #tablename = [devicelogs_1_]
END
ELSEIF MONTH(GETDATE()) = 2
BEGIN
SET #tablename = '[devicelogs_2_]
END
ELSEIF MONTH(GETDATE()) = 3
BEGIN
SET #tablename = [devicelogs_3_]
END
ELSEIF MONTH(GETDATE()) = 4
BEGIN
SET #tablename = [devicelogs_4_]
END
ENDIIF MONTH(GETDATE()) = 5
BEGIN
SET #tablename = [devicelogs_5_]
END
ELSEIF MONTH(GETDATE()) = 6
BEGIN
SET #tablename = [devicelogs_6_]
END
ELSEIF MONTH(GETDATE()) = 7
BEGIN
SET #tablename = [devicelogs_7_]
END
ELSEIF MONTH(GETDATE()) = 8
BEGIN
SET #tablename = [devicelogs_8_]
END
ELSEIF MONTH(GETDATE()) = 9
BEGIN
SET #tablename = [devicelogs_8_]
END
ELSEIF MONTH(GETDATE()) = 10
BEGIN
SET #tablename = [devicelogs_10_]
END
ELSEIF MONTH(GETDATE()) = 11
BEGIN
SET #tablename = [devicelogs_11_]
END
ELSEIF MONTH(GETDATE()) = 12
SET #tablename = [devicelogs_12_]
END
SET #yearnam = YEAR(GETDATE());
SET #tabnam = #tablename + #yearnam;
-- Execute a query
DECLARE #query_a AS nvarchar(500);
SET #query_a = 'INSERT INTO etimetracklite1.dbo.devicelogs SELECT *
FROM etimetracklite1.dbo.' + [#tabnam];
EXECUTE sp_executesql #query_a;
The error I am getting is SQL error 102.
remove single quote from this condition
ELSEIF MONTH(GETDATE()) = 2
BEGIN
SET #tablename = '[devicelogs_2_]
END
and ELSEIF should be ELSE IF
This is a lousy data model. You should be putting all the data into a single table.
If you printed out the SQL, you would probably spot the problem very easily. (At least) one problem is the misconstructed square braces. You have the year coming after them, for instance.
But, in any case, you can simplify your code:
TRUNCATE TABLE [etimetracklite1].[dbo].[devicelogs];
-- Create table
DECLARE #tabnam AS nvarchar(18);
SET #tabname = 'devicelogs_11_[MM][YYYY]';
SET #tabname = REPLACE(REPLACE(#tabname, '[MM]', MONTH(GETDATE())
), '[YYYY]', YEAR(GETDATE())
);
DECLARE #sql nvarchar(max);
SET #sql = 'INSERT INTO etimetracklite1.dbo.devicelogs SELECT *
FROM etimetracklite1.dbo.' + #tabnam;
EXECUTE sp_executesql #sql;
I have one parent stored procedure and one nested stored procedure. Parent Stored procedure calls the nested stored procedure on loop. Now when there is certain condition matches I have raised the error. When this error is raised I want to stop all the process and return the error.
CREATE Proc [dbo].[Usp_GenSalarySheet](#SalData [HRM].UTDT_SalaryData ReadOnly)
AS
set nocount on
DECLARE #SMT NVARCHAR(MAX)
SET #SMT = 'Create Table ##SalarySheet (StaffID INT,FullName NVARCHAR(1024),PresentDays NVARCHAR(1024),Absent NVARCHAR(1024),Department NVARCHAR(1024),Designation NVARCHAR(1024),'
DECLARE #HopName nvarchar(max)
Declare HOPCursor cursor for select ID from HRM.tbl_HOP
OPEN HOPCursor
FETCH NEXT FROM HOPCursor INTO #HopName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SMT = #SMT + ' [' + #HopName + '] DECIMAL(19,7),'
FETCH NEXT FROM HOPCursor into #HopName
END
SET #SMT = #SMT + '[Total] DECIMAL(19,7))'
CLOSE HOPCursor
DEALLOCATE HOPCursor
print (#smt)
exec (#SMT)
select * into #temp from #SalData
Declare #TopID INT
While (Select Count(*) From #Temp) > 0
Begin
Select Top 1 #TopID = StaffID From #temp
Declare #StaffID INT =(select top 1 StaffID from #temp)
Declare #StaffName NVARCHAR(1024) = (SELECT TOP 1 FullName FROM #temp)
Declare #WorkingDays Int = (SELECT top 1 WorkingDays from #temp)
Declare #Leave INT = (SELECT top 1 [Absent] from #temp)
INSERT INTO ##SalarySheet(StaffID,FullName,[Absent]) values(#StaffID,#StaffName,#Leave)
DECLARE #HOPType INT
DECLARE #Value Decimal(19,7)
DECLARE #CalcVal DECIMAL(19,7) = 0
DECLARE #Formula NVARCHAR(MAX)
DECLARE #Total DECIMAL(19,7)
DECLARE #PayEvery INT
DECLARE #Round Int
Declare HOPList Cursor for SELECT ID,HOPType,Value,Formula,RoundOff,PayEvery FROM HRM.Tbl_HOP order by Schedule
open HOPList
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
WHILE ##FETCH_STATUS = 0
BEGIN
if exists(select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = #StaffID and HOPID = #HopName)
print('select * from HRM.[Tbl_ContractHOPDetails] where PersonalDetailsID = ' + convert(varchar(max), #StaffID) + ' and HOPID =' + convert(varchar(max),#HopName))
begin
if(#HOPType=51)
begin
exec HRM.Usp_GetSalaryValueFromFormula #StaffID,#Formula,#HOPType,#Leave,#WorkingDays,#Value output
set #HOPType= 50
end
if(#HOPType=50)
begin
set #CalcVal = #value
END
IF(#HOPType=38)
BEGIN
SET #CalcVal = #Value - ((#Value/#WorkingDays) * #Leave)
END
if(#PayEvery= 40)
begin
set #CalcVal = ((#CalcVal * #WorkingDays) - (#CalcVal * #Leave))
end
if(#Round = 45)
begin
set #CalcVal = round(#CalcVal,2)
end
else if(#Round = 46)
begin
set #CalcVal = CEILING(#CalcVal)
end
else if(#Round = 47)
begin
set #CalcVal = FLOOR(#CalcVal)
end
set #SMT ='UPDATE ##SalarySheet SET [' + #HopName + '] = ' + cast(#CalcVal as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
end
SET #CalcVal = 0
FETCH NEXT FROM HOPList INTO #HopName,#HOPType,#Value,#Formula,#Round,#PayEvery
END
close HOPList
DEALLOCATE HOPList
set #SMT ='UPDATE ##SalarySheet SET [Total] = ' + cast(#Total as nvarchar(max)) + ' where StaffID = ' + cast(#StaffID as nvarchar(max))
exec (#smt)
Delete #temp Where StaffID = #TopID
end
select * from ##SalarySheet
drop table ##SalarySheet
This is my parent Stored Procudere and nested procedure is as follow:
CREATE proc [HRM].[Usp_GetSalaryValueFromFormula](#StaffID INT,#val nvarchar(max),#HOPType INT,#Leave INT,#WorkingDays INT, #GetResult Decimal(19,7) output)
as
set nocount on
Declare #Formula Varchar(max)
declare #initial INT =0
declare #final INT =0
Declare #DataVal NVARCHAR(MAX) -- set the value from HOP table
declare #FieldVal nvarchar(max)
declare #cnt int = 0
Declare #Complete Int =CHARINDEX ('[',#val,0)
while (#Complete <> 0)
begin
set #initial = CHARINDEX ('[',#val,0)
set #final = CHARINDEX(']',#val,0)
set #FieldVal = SUBSTRING(#val,#initial,(#final-#initial) + 1)
if len(#FieldVal)<>0
begin
select #HOPType = HOPType, #DataVal= ( case when HOPType = 51 then [Formula] else cast([Value] as nvarchar(max)) end) from HRM.Tbl_ContractHOPDetails where PersonalDetailsID = #StaffID and HOPID in(select ID from HRM.tbl_HOP where HOPName = replace(replace(#fieldVal,'[',''),']',''))
if (#DataVal is null or #DataVal ='')
begin
RAISERROR ('Nested HOP is not defined.',11,1)
RETURN
end
print(#DataVal)
if ISNUMERIC(#DataVal)=1
begin
if(#HOPType = 38)
begin
SET #DataVal = cast(#DataVal as decimal(19,7)) - ((cast(#DataVal as decimal(19,7))/#WorkingDays) * #Leave)
end
end
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('[',#val,0)
set #fieldVal =''
set #final =0
set #initial = 0
end
SET #Complete =CHARINDEX ('{',#val,0)
while (#Complete <> 0)
BEGIN
set #initial = CHARINDEX ('{',#val,0)
set #final = CHARINDEX('}',#val,0)
set #FieldVal = SUBSTRING(#val,#initial+1,(#final-#initial)-1)
if len(#FieldVal)<>0
begin
set #DataVal = isnumeric((SELECT 0 FROM [HRM].Tbl_StaffTag where CValue = #FieldVal and StaffID = #StaffID))
set #FieldVal = '{' + #FieldVal + '}'
set #val = replace(#val,#fieldVal,#DataVal)
set #fieldVal= ''
set #DataVal = ''
end
set #Complete = CHARINDEX ('{',#val,0)
set #final =0
set #initial = 0
END
DECLARE #RetrunVal DECIMAL(19,7)
declare #ParmDefinition Nvarchar(512) = '#GetVal decimal(19,7) OUTPUT'
Declare #SMT NVARCHAR(MAX) = ' SET #GetVal = ' + #val
EXECUTE sp_executeSQL #Smt, #ParmDefinition, #GetVal =#RetrunVal OUTPUT
set #GetResult = #RetrunVal
But in current situation it raises error and again from the main procedure it runs next step of loop. But I want to terminate the complete process after this raiserror
Kindly help me
My guess is that RaiseError throws the control back to the caller, which might make the Return statement unreachable. The caller (loop) continues with next iteration.
I am trying to set a variable as a query result. My problem is that below code runs in a while loop & schemaName is always different.
WHILE (#i <= (SELECT MAX(idx) FROM #schema_table))
BEGIN
SET #userid = (SELECT AspNetUsers.Id
FROM schemaName.AspNetUsers
LEFT JOIN schemaNameAspNetUserRoles ON AspNetUserRoles.UserId = AspNetUsers.Id
LEFT JOIN schemaName.AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId
WHERE AspNetRoles.Name = 'SuperAdmin')
END
How to set schemaName as variable so that it can be dynamic in the while loop.
Something like this will help:
DECLARE #sql nvarchar(4000),
#schemaName nvarchar(200),
#i int = 1,
#vParams nvarchar(100)
SET #vParams = '#uid int OUTPUT'
WHILE (#i <= (SELECT MAX(idx) FROM #schema_table))
BEGIN
SELECT #schemaName = schemaName
FROM #schema_table
WHERE idx = #i
SELECT #sql = '
SELECT #userid = AspNetUsers.Id
FROM schemaName.AspNetUsers
LEFT JOIN schemaNameAspNetUserRoles ON AspNetUserRoles.UserId = AspNetUsers.Id
LEFT JOIN [' +#schemaName + '].AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId
WHERE AspNetRoles.Name = ''SuperAdmin'';'
EXEC sp_executesql #sql, #vParams, #userid=#uid OUTPUT
-- here you hot #userid with value you need and can do something with it
SET #i = #i + 1
END
I am very new to SQL Server and finally got my code to run, but its very slow. My database is a bit on the big side (1.22mill rows, 3 columns) and I have some while loops, which I know isn't ideal but I couldn't find a way around it.
Any help would be greatly appreciated!!!
declare #b float
declare #c float
declare #dateloopfora datetime
declare #dateloopforc datetime
BEGIN
SET #MYCURSOR = CURSOR FOR
SELECT DISTINCT [STOCKS] FROM [tsxvPrices].[dbo].[3coldata]
OPEN #MYCURSOR
FETCH NEXT FROM #MYCURSOR INTO #STOCK
set #end = '12/30/2012'
WHILE ##FETCH_STATUS = 0
BEGIN
print ('Stockname restart: ' + #stock)
SET #dateloop = '01/01/2012'
WHILE (#dateloop <= #end)
BEGIN
set #datedelta = 0
SET #dateloop = dateadd(day,1,#dateloop)
set #b = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = #dateloop and [stocks] = #stock))
WHILE (#datedelta < 4)
BEGIN
set #datedelta = #datedelta + 1
if (#b is null)
begin
SET #dateloop = dateadd(day,1,#dateloop)
set #b = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = #dateloop and [stocks] = #STOCK))
/*print ('b= ' + cast( #b as varchar(10)) + ' dateadd1=' + cast( #datedelta as varchar(10))) */
end
END
SET #datedelta = 0
set #a = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = dateadd(day,-1,#dateloop) and [stocks] = #stock))
set #c = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = dateadd(day,+96,#dateloop) and [stocks] = #stock))
if #b/#a < 0.8
begin
WHILE (#datedelta < 4)
BEGIN
set #datedelta = #datedelta + 1
if (#a is null)
begin
SET #dateloopfora = dateadd(day,-#datedelta,#dateloop)
set #a = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = #dateloopfora and [stocks] = #STOCK))
/*print ('b= ' + cast( #b as varchar(10)) + ' dateadd1=' + cast( #datedelta as varchar(10))) */
end
if (#c is null)
begin
SET #dateloopforc = dateadd(day,96+#datedelta,#dateloop)
set #c = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = #dateloopforc and [stocks] = #STOCK))
/*print ('b= ' + cast( #b as varchar(10)) + ' dateadd1=' + cast( #datedelta as varchar(10))) */
end
END
/*print ('Stockname: ' + #stock)
print #dateloop
print('daily')
print #b/#a
print ('quarterly')*/
print #c/#b
/*print ('======================')*/
end
END
FETCH NEXT FROM #MYCURSOR INTO #STOCK
END
CLOSE #MYCURSOR
DEALLOCATE #MYCURSOR
I can see one simple problem straight away, you're using a Cursor.
This is probably one of the worst ways to process SQL, it's very slow and it's forcing the SQL engine to be very inefficient.
You're new to SQL so I'll forgo a technical explanation, but please have a look at this other StackOverflow question:
Why is it considered bad practice to use cursors in SQL Server?
I may be able to offer further advice, What version of SQL are you using?
I want it to count then if #intcount > 0 it should show data or else no data found, but when I execute it gives me 'no data found' regardless, what am I doing wrong?
#FiscalYear int,
#SchoolID int,
#Status int
AS
BEGIN
SET NOCOUNT ON;
declare #sqlstr varchar(2000)
declare #intCount int
set #intCount = 0
set #sqlstr = 'Select #intCount = Count(*)
From PrivateSchool left outer join Attachment on Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
inner join FiscalYearPrivateSchool fp ON fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
Where (FiscalYear = '+convert(varchar, #FiscalYear)+') AND (PrivateSchool.IsActive = 1)'
IF (#SchoolID != -1)
SET #sqlstr = #sqlstr + ' AND SchoolID ='+ convert(varchar, #SchoolID)
IF (#Status = -1)
SET #sqlstr = #sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else IF (#Status = 1)
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID is Null'
If (#intCount > 0)
BEGIN
set #sqlstr= 'Select SchoolName as School,
(Case when Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID THEN ''Uploaded''
ELSE ''Not Uploaded'' END) AS Status,
COUNT(Attachment.PrivateSchoolID) AS [Count]
From PrivateSchool left outer join Attachment on Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID
inner join FiscalYearPrivateSchool fp ON fp.PrivateSchoolID = PrivateSchool.PrivateSchoolID
Where (FiscalYear = '+convert(varchar, #FiscalYear)+') AND (PrivateSchool.IsActive = 1)'
IF (#SchoolID != -1)
SET #sqlstr = #sqlstr + ' AND SchoolID ='+ convert(varchar, #SchoolID)
IF (#Status = -1)
SET #sqlstr = #sqlstr + ' AND PrivateSchool.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else IF (#Status = 1)
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID = PrivateSchool.PrivateSchoolID'
Else
SET #sqlstr = #sqlstr + ' AND Attachment.PrivateSchoolID is Null'
SET #sqlstr = #sqlstr + ' Group by SchoolName, Attachment.PrivateSchoolID, PrivateSchool.PrivateSchoolID'
SET #sqlstr = #sqlstr + ' Order By SchoolName'
EXEC(#sqlstr)
END
ELSE
Select 'No Data Found' as 'FileUpload'
END
You need:
EXEC sp_executesql #sqlstr, N'#intCount INT OUTPUT', #intCount = #intCount OUTPUT;
IF (#intCount > 0)
BEGIN
....
END
You'll also need to make #sqlstr NVARCHAR(2000) and add set it to N'SELECT ...' as opposed to 'SELECT ...' - that leading N can be important.
The problem is:
declare #intCount int
set #intCount = 0
...
<a bunch of code where #intcount doesn't change>
If (#intCount > 0)
It's always going to be 0.
Your issue is one of scope. The EXEC(#sqlstr) command doesn't have access to the #intcount variable in your stored procedure. I would bet if you ran this code in a query window, it would tell you to declare #intcount.
Listen to YUCK and rewrite this to avoid dynamic SQL, and then your SELECT will be able to set the #intcount variable.