Invalid column name '#Results' - sql-server

alter PROCEDURE sp_Get_CustInfoSerach2
(#PageIndex INT = 1
,#PageSize INT = 10
,#RecordCount INT OUTPUT
,#ColumnName VARCHAR(50)=null
,#Value VARCHAR(50)=null
,#ddlValue VARCHAR(50)=null
,#txtValue VARCHAR(50)=null
,#status varchar(30))
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
if #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
else if #ddlValue IS NULL
begin
SET #Value = ''''+#txtValue+ ''''
end
SET #cmd = 'SELECT ROW_NUMBER() OVER
(
ORDER BY C_Register.UserId desc
)AS RowNumber
,C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO'+ #Results+'
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results
EXEC(#cmd)
END
throwing error:
Invalid column name '#Results'.
how to solve it?

If i understand your problem correctly you should first exec dynamic sql before select from temporary table
Alter PROCEDURE sp_Get_CustInfoSerach2
(
#PageIndex INT = 1 ,
#PageSize INT = 10 ,
#RecordCount INT OUTPUT ,
#ColumnName VARCHAR(50)=null ,
#Value VARCHAR(50)=null ,
#ddlValue VARCHAR(50)=null ,
#txtValue VARCHAR(50)=null ,
#status varchar(30)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #cmd AS NVARCHAR(max)
If #txtValue IS NULL
Begin
SET #Value = ''''+#ddlValue+ ''''
End
Else
if #ddlValue IS NULL
Begin
SET #Value = ''''+#txtValue+ ''''
End
SET #cmd = 'SELECT ROW_NUMBER() OVER ( ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName, C_Register.Status,
Packages.PackagePeriod, Packages.PackageName, C_Register.ActivationDate,
Receive_Payment.OldExpiryDate, Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName, C_Register.Address,C_Register.CreatedDate
INTO #Results
FROM C_Register INNER JOIN Receive_Payment ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = '+#status+'And
' + #ColumnName + ' = ' + #Value
/*First Execute above dynamic Sql query */
EXEC(#cmd)
/* From the above execute statemnet the query will executed and temporary table will created on the fly */
SELECT #RecordCount = COUNT(*)
FROM #Results
SELECT * FROM #Results
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #Results

Problem in your query is creation of temp table thats not right way to create temp table inside dynamic query.
But even if you create temp table inside a dynamic query it can be accessed only inside the session of dynamic query. If you try to select the temp outside of dynamic query which is created inside the dynamic query you will get a error saying object doesnot exist.
Since you know the number of columns present in the result of dynamic query you can create the temp table outside of dynamic query and insert the records through dynamic query.
Try changing your procedure like this.
ALTER PROCEDURE Sp_get_custinfoserach2 (#PageIndex INT = 1,
#PageSize INT = 10,
#RecordCount INT output,
#ColumnName VARCHAR(50)=NULL,
#Value VARCHAR(50)=NULL,
#ddlValue VARCHAR(50)=NULL,
#txtValue VARCHAR(50)=NULL,
#status VARCHAR(30))
AS
BEGIN
SET nocount ON;
DECLARE #cmd AS NVARCHAR(max)
IF #txtValue IS NULL
BEGIN
SET #Value = '''' + #ddlValue + ''''
END
ELSE IF #ddlValue IS NULL
BEGIN
SET #Value = '''' + #txtValue + ''''
END
/*create a temp as same structure of your dynamic query select statement*/
CREATE TABLE #result
(
rownum INT,
userid INT,
NAME VARCHAR(100),
username VARCHAR(100),
status VARCHAR(15),
packageperiod VARCHAR(15),
packagename VARCHAR(100),
activationdate DATETIME,
oldexpirydate DATETIME,
balance NUMERIC(22, 4),
pyingamount NUMERIC(22, 4),
lastpaiddate DATETIME,
lastupdatetime DATETIME,
areaname VARCHAR(100),
mobno INT,
empname VARCHAR(100),
address VARCHAR(5000),
createddate DATETIME
)
SET #cmd =
' Insert into #result
SELECT ROW_NUMBER() OVER (ORDER BY C_Register.UserId desc )AS RowNumber,
C_Register.UserId, C_Register.Name, C_Register.UserName,
C_Register.Status, Packages.PackagePeriod, Packages.PackageName,
C_Register.ActivationDate,Receive_Payment.OldExpiryDate,
Receive_Payment.Balance, Receive_Payment.PyingAmount,
Receive_Payment.LastPaidDate, C_Register.LastUpdateTime,
Area.AreaName, C_Register.MobNo, Employee.EmpName,
C_Register.Address,C_Register.CreatedDate
FROM C_Register
INNER JOIN Receive_Payment
ON C_Register.UserId = Receive_Payment.UserId
INNER JOIN Area
ON C_Register.AreaId = Area.AreaId
INNER JOIN Employee
ON Receive_Payment.EmpId = Employee.EmpId
INNER JOIN Packages
ON Receive_Payment.PackageId = Packages.PackageId
where C_Register.AccountExpiry= Receive_Payment.OldExpiryDate And C_Register.Status = ' + #status + ' And ' + #ColumnName + ' = ' + #Value
SELECT #RecordCount = Count(*)
FROM #results
SELECT *
FROM #results
WHERE rownumber BETWEEN( #PageIndex - 1 ) * #PageSize + 1 AND( (
( #PageIndex - 1 ) * #PageSize + 1 ) +
#PageSize ) - 1
DROP TABLE #results
EXEC(#cmd)
END
Note : I have given generic datatypes to temp table columns please change the datetypes according to your schema.

Related

Getting an error when executing string query "An object or column name is missing or empty"

My SQL Query working fine with "EXEC(Query)"
I added "SELECT * INTO #TempData" code before "EXEC(Query)" to insert all the records into a single table instead of multiple separate table records. but getting that error. I even added Aliases but still getting that error. Please suggest. Thanks!
With Temp AS
(SELECT companyID,DBName, ROW_NUMBER()over(order by dbname) as [Rownumber]
from CentralHub.dbo.Company where companyID in (16,66,101,196,94,210,215,26,37,194,179))
SELECT * INTO #temp FROM Temp
Declare #Count INT = 1;
Declare #Query Varchar(MAX);
Declare #Dbname Varchar(MAX);
Declare #ID INT;
WHILE(#Count <= (SELECT count(companyID) from #temp))
BEGIN
SET #Dbname = (SELECT dbname from #temp where Rownumber = #Count);
SET #ID = (SELECT companyID from #temp where Rownumber = #Count);
SET #Query = '
USE [Db]
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = ''dbo''
AND TABLE_NAME = ''RQSalesFlatten''))
BEGIN
IF(EXISTS(SELECT top 1 1 FROM RQSalesFlatten ))
BEGIN
SELECT [ID] AS [CompanyID],''[Db]'' AS [DbName], max(rqDate) AS [LastSalesDate] FROM RQSalesFlatten
END
ELSE
SELECT [ID] AS [CompanyID],''[Db]'' AS [DbName], max(invoiceDate) AS [LastSalesDate] FROM Sales_Flatten
END
ELSE
BEGIN
SELECT [ID]AS [CompanyID],''[Db]'' AS [DbName], max(invoiceDate)AS [LastSalesDate] FROM Sales_Flatten;
END
';
SET #Query = Replace(#Query,'[Db]',#Dbname);
SET #Query = Replace(#Query,'[ID]',#ID);
SELECT * INTO #TempData EXEC(#Query);
SET #Count = #Count+1;
END

How to eliminate column with same name using self join?

In this stored procedure, I have to use
SELECT *
FROM #policyData a
LEFT OUTER JOIN ##Temp b ON b.qguid = a.quoteguid
LEFT OUTER JOIN ##Temp c ON c.qguid = a.quoteguid2;
And because of that I have two columns with the same name "QuoteGuid".
Then when I try to add this query in SSRS, I get an error, because I have 2 columns with the same name.
I am not the author of this stored procedure, so I cannot understand is any chance to eliminate or rename column name that causing this.
CREATE PROCEDURE dbo.SP_Catalytic_WindEQRenewalExtract
#pos INT,
#len INT,
#value varchar(8000),
#PriorDays INT,
#PastDays INT,
#LineName varchar(50)
AS
SET NOCOUNT ON;
SELECT #LineName ='wind'
SELECT #PriorDays= -15
SELECT #PastDays = 55
DECLARE #policyData TABLE
(
NamedInsured varchar(1000),
displaystatus varchar(100),
quoteguid uniqueidentifier,
quoteid int,
controlno int,
ExpirationDate datetime,
MonthName nvarchar(25),
ExpiringPremium money,
Underwriter varchar(250),
linename varchar(25),
RenewalSubmissionRecieved varchar(5),
QuotedPremium money,
quoteguid2 uniqueidentifier,
controlno2 int,
displaystatus2 varchar(50),
quotestatuscomment varchar(2500),
quotestatusreasoncomment varchar(2500),
BoundPremium money,
Underwriter2 varchar(500)
)
INSERT INTO #policyData
EXEC ('Catalytic_sp_FetchRenewalPolicy ' + #PriorDays + ',' + #PastDays + ', ' + #LineName + '')
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode)
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename =#LineName order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
IF OBJECT_ID('tempdb.dbo.##Temp', 'U') IS NOT NULL
DROP TABLE ##Temp;
set #query =
'select * into ##Temp
from
(SELECT QUOTEGUID as qguid, ' + #cols + ' from
(
select QuoteGUID, LocationCode, LineName,LineGUID
--from Catalytic_vw_PolicyLocationCode where quoteguid=''99D60178-C33B-4A3F-9EA7-0001EF31626A''
from Catalytic_vw_PolicyLocationCode
) x
pivot
(
max(locationCode)
for locationCode in (' + #cols + ')
)p)x'
EXEC sp_executesql #query;
set #pos = 0
set #len = 0
WHILE CHARINDEX(',', #cols, #pos+1)>0
BEGIN
set #len = CHARINDEX(',', #cols, #pos+1) - #pos
set #value = SUBSTRING(#cols, #pos, #len)
-- PRINT #value
set #pos = CHARINDEX(',', #cols, #pos+#len) +1
declare #sql nvarchar (1000);
set #sql = N'update ##Temp set ' + #value + '= ''X'' where len(' + #value + ') > 0 ' ;
exec sp_executesql #sql;
END
SELECT *
FROM
#policyData a
LEFT OUTER JOIN ##Temp b on b.qguid = a.quoteguid
/*Because I am using another LEFT JOIN here, I have two columns namem "qguid"*/
LEFT OUTER JOIN ##Temp c on c.qguid = a.quoteguid2;
DROP TABLE ##Temp;
just change where you are trying to make another left join in the last and explicitly mention all column name.
SELECT a.* ,b.*,c.qguid as qguid1
FROM
#policyData a
LEFT OUTER JOIN ##Temp b on b.qguid = a.quoteguid
/*Because I am using another LEFT JOIN here, I have two columns namem "qguid"*/
LEFT OUTER JOIN ##Temp c on c.qguid = a.quoteguid2;
Another way,
declare #CurDate datetime=getdate()
Declare #CurDate1 varchar(8)
select #CurDate1= replace(convert(varchar(8), #CurDate, 112), ':','')
select #CurDate1
SET #cols = STUFF((SELECT ',' + QUOTENAME(c.locationCode) +#CurDate1
FROM Catalytic_vw_LocationCodeByLine c WHERE c.linename =#LineName order by c.CompanyName, c.LocationCode
FOR XML PATH('')),1,1,'')
If I am understanding your question correctly you need to use an existing stored procedure to get data for an SSRS report and you cannot modify the procedure. The problem is the stored procedure returns two columns with the same name and SSRS will not accept that in a dataset.
To get around that call the stored procedure and store its results in a temp table with different column names. Then output the temp table contents. This gives you fill control over the name of the columns. See example below.
CREATE PROCEDURE dbo.sp_Test
AS
BEGIN
SELECT
1 AS 'Test1',
2 AS 'Test2',
3 AS 'Test3',
3 AS 'Test3'
END
CREATE TABLE #Test
(
Test1 int,
Test2 int,
Test3 int,
Test4 int
)
INSERT INTO #Test
EXEC dbo.sp_Test
SELECT * FROM #Test
DROP TABLE #Test

How to replace while loop?

I've tried to simplify following sql query, it takes more time due to the while loop.
DECLARE #TEMP TABLE
(
ID NUMERIC(18,0) IDENTITY (1, 1) PRIMARY KEY NOT NULL,
NAME VARCHAR(1000),
CATEGORY_ID INT,
TYPE1 VARCHAR(100),
VALUE VARCHAR(6000),
TYPE2 VARCHAR(100)
)
INSERT INTO #TEMP
SELECT
NAME ,
A.CATEGORY_ID,
A.TYPE1,
A.VALUE,
A.TYPE2
FROM
DBO.TABLE1 A,
DBO.TABLE2 B
WHERE
A.CATEGORY_ID=B.CATEGORY_ID
ORDER BY A.CATEGORY_ID
DECLARE #ROWCNT INT=1 , #ROWS INT=0 , #NAME VARCHAR(100),#TYPE1 VARCHAR(100)
,#STAT CHAR(1)='Y'
, #VALUE VARCHAR(6000)
,#COND VARCHAR(8000)
, #TYPE2 VARCHAR(100)
SELECT #COND='SELECT * FROM TABLE3 '
SELECT #ROWCNT = #ROWCNT , #ROWS = (#ROWCNT-1)+ COUNT(1) FROM #TEMP
WHILE #ROWCNT <= #ROWS
BEGIN
SELECT #NAME = NAME ,
#TYPE1 = LTRIM(RTRIM(TYPE1)) ,
#VALUE = VALUE,
#TYPE2 = ISNULL(TYPE2,'')
FROM #TEMP WHERE ID = #ROWCNT
IF #STAT='Y'
BEGIN
IF #TYPE1 = 'SQL'
BEGIN
SELECT #COND=#COND + ' A'+'.'+(#NAME)+' '+#TYPE1+ ' ('''+#VALUE+''') '+#TYPE2+' '+CHAR(13)
END
ELSE
BEGIN
SELECT #COND=#COND + ' A'+'.'+(#NAME)+' '+#TYPE1+ ''''+#VALUE+''' '+#TYPE2+' '++CHAR(13)
END
END
SELECT #ROWCNT=#ROWCNT+1;
END
PRINT (#COND)
the important thing to replace while loop instead of CTE or something else.
can any one sort up this problem.Thanks in advance
It looks like you need something like the below.
DECLARE #COND VARCHAR(8000) ='SELECT * FROM TABLE3 '
+ (SELECT ' A' + '.' + NAME + ' ' + LTRIM(RTRIM(TYPE1))
+ CASE
WHEN LTRIM(RTRIM(TYPE1)) = 'SQL' THEN ' (''' + VALUE + ''') '
ELSE VALUE
END
+ ISNULL(TYPE2, '') + ' ' + CHAR(13)
FROM #TEMP
ORDER BY ID
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(8000)');
PRINT #COND
The string generated isn't valid SQL though

Why it shows converting data type varchar to int in sql server?

**
I have make a Stored procedure in sql-server 2008 for search
purpose,Below code represents my stored procedure, while executing
stored procedure it gives error like conversion failed varchar to data
type int
**
ALTER PROCEDURE [dbo].[SUMMARY_DETAILS_PROJECT_SEARCH_MAP]
#PROJECT_CAT INT=NULL,
#PROJECT_TYPE INT=NULL,
#ADDRESS VARCHAR(150)=NULL,
#MIN_PRICE INT=NULL,
#MAX_PRICE INT=NULL,
#BEDROOM VARCHAR(150)=NULL
AS
CREATE TABLE #TEMP_MAP
(
SN INT IDENTITY,
PROJECT_ID INT,
PROJECT_NAME VARCHAR(100),
LAT VARCHAR(50),
LONG VARCHAR(50),
PROJECT_LOC VARCHAR(150),
MIN_PRICE VARCHAR(100),
MAX_PRICE VARCHAR(100),
PROJECT_IMAGE VARCHAR(250)
)
DECLARE #SQL NVARCHAR(MAX),#PARAMETER_LIST NVARCHAR(MAX)
DECLARE #COUNT_ZONE INT
DECLARE #COUNT_CITY INT
SELECT #COUNT_ZONE= (SELECT COUNT(*) FROM ZONE_MASTER WHERE ZONE_NAME LIKE #ADDRESS + '%')
SELECT #SQL = ('SELECT PROJECT_ID FROM PROJECTS WHERE STATUS=1')
IF(#PROJECT_CAT !=0)
SELECT #SQL = #SQL+' AND PROJECT_CAT_ID=#XP_PROJECT_CAT'
IF(#PROJECT_TYPE !=0)
SELECT #SQL = #SQL+' AND PROJECT_TYPE_ID=#XP_PROJECT_TYPE'
IF(#COUNT_ZONE !=0)
SELECT #SQL = #SQL+' AND ZONE_ID IN (SELECT ZONE_ID FROM ZONE_MASTER WHERE ZONE_NAME LIKE '''+#ADDRESS+''' + ''%'')'
ELSE
SELECT #SQL = #SQL+' AND BLOCK_ID IN (SELECT BLOCK_ID FROM BLOCK_MASTER WHERE BLOCK_NAME LIKE '''+#ADDRESS+''' + ''%'')'
IF(#MIN_PRICE !=0)
SELECT #SQL = #SQL+' AND MIN_ID >=#XP_MIN_PRICE'
IF(#MAX_PRICE !=0)
SELECT #SQL = #SQL+' AND MAX_ID <=#XP_MAX_PRICE'
IF(#BEDROOM !='')
SELECT #SQL = #SQL+' AND BEDROOM=#XP_BEDROOM'
SELECT #SQL = #SQL + ' ORDER BY PROJECT_ENTRY_DATE DESC '
SELECT #PARAMETER_LIST = '#XP_PROJECT_CAT INT,#XP_PROJECT_TYPE INT,#XP_MIN_PRICE INT,#XP_MAX_PRICE INT,#XP_BEDROOM VARCHAR(100)'
INSERT INTO #TEMP_MAP (PROJECT_ID)
EXEC SP_EXECUTESQL #SQL,#PARAMETER_LIST,'#XP_PROJECT_CAT','#XP_PROJECT_TYPE','#XP_MIN_PRICE','#XP_MAX_PRICE','#XP_BEDROOM'
PRINT #SQL
UPDATE #TEMP_MAP SET
PROJECT_NAME = P.PROJECT_NAME,
LAT = P.PROJECT_LAT,
LONG = P.PROJECT_LONG,
PROJECT_LOC = P.PROJECT_LOC,
MIN_PRICE = P.MAX_PRICE,
MAX_PRICE = P.MIN_PRICE,
PROJECT_IMAGE = './UploadImage/Upload_Project/' + P.PROJECT_NAME +'/' + 'Google' + '/' + [IMG1]
FROM Projects P WHERE P.PROJECT_ID=#TEMP_MAP.PROJECT_ID
SELECT * FROM #TEMP_MAP
DROP TABLE #TEMP_MAP
It is because you are putting single quotes around the values you are passing to sp_executesql, e.g:
EXEC SP_EXECUTESQL #SQL,#PARAMETER_LIST,'#XP_PROJECT_CAT'
Here you are not passing the integer value of #XP_PROJECT_CAT, but you are passing the string '#XP_PROJECT_CAT', and the procedure is expecting an int.
As an aside, I am not sure why you have opted for parameterising everything apart from address? Surely it would make sense to parameterise this too - e.g.
IF(#COUNT_ZONE !=0)
SELECT #SQL = #SQL+' AND ZONE_ID IN (SELECT ZONE_ID
FROM ZONE_MASTER
WHERE ZONE_NAME LIKE #ADDRESS + ''%'')'
ELSE
SELECT #SQL = #SQL+' AND BLOCK_ID IN (SELECT BLOCK_ID
FROM BLOCK_MASTER
WHERE BLOCK_NAME LIKE #ADDRESS + ''%'')'
Then add #Address as a parameter to sp_executesql

Execute Stored Procedure against multiple tables

I want to execute below stored procedure against multiple tables, by passing table name as parameter.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE PROCEDURE GETARTICLESPAGEWISE
#PageIndex INT = 1
,#PageSize INT = 10
,#ArticleCategory varchar(100) = 'null'
,#RecordCount INT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER
(
ORDER BY [ArticleID] ASC
)AS RowNumber
,[ArticleID]
,[ArticleName]
,[ArticleCategory]
INTO #ResultSet
FROM [ASPDOTNETARTICLES]
WHERE ArticleCategory = #ArticleCategory
SELECT #RecordCount = COUNT(*)
FROM #ResultSet
SELECT * FROM #ResultSet
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #ResultSet
END
GO
--EXEC dbo.GETARTICLESPAGEWISE #PageIndex =1, #PageSize = 2, #ArticleCategory='Gridview',#RecordCount=0
I tried but error occurred, tried stored procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE GETARTICLESPAGEWISEGENERIC
#PageIndex INT = 1
,#PageSize INT = 10
,#ArticleCategory varchar(100) = 'null'
,#RecordCount INT OUTPUT
,#TableName varchar(100) = 'NULL'
AS
BEGIN
DECLARE #columnList varchar(200)
SET #columnList=' SELECT ROW_NUMBER() OVER
(
ORDER BY [ArticleID] ASC
)AS RowNumber
,[ArticleID]
,[ArticleName]
,[ArticleCategory]'
SET NOCOUNT ON;
DECLARE #sqlCommand varchar(300)
set #sqlCommand ='
SELECT '+ #columnList +'
INTO #ResultSet
FROM '+ #TableName +'
WHERE ArticleCategory ='+ #ArticleCategory+'
//i got the error in this statement
SELECT #RecordCount = COUNT(*)
FROM #ResultSet
SELECT * FROM #ResultSet
// i got the error in this statement
WHERE RowNumber BETWEEN(#PageIndex -1) * #PageSize + 1 AND(((#PageIndex -1) * #PageSize + 1) + #PageSize) - 1
DROP TABLE #ResultSet'
END
GO
Can u give solution for this problem?
Try this one -
CREATE PROCEDURE GETARTICLESPAGEWISE
#PageIndex INT = 1
, #PageSize INT = 10
, #ArticleCategory VARCHAR(100) = 'null'
, #TableName VARCHAR(100) = 'dbo.ASPDOTNETARTICLES'
, #RecordCount INT OUTPUT
AS BEGIN
SET NOCOUNT ON;
IF OBJECT_ID (N'tempdb.dbo.##ResultSet') IS NOT NULL
DROP TABLE ##ResultSet
DECLARE #SQL NVARCHAR(MAX) = '
SELECT
RowNumber = ROW_NUMBER() OVER (ORDER BY ArticleID)
, ArticleID
, ArticleName
, ArticleCategory
INTO ##ResultSet
FROM ' + #TableName + '
WHERE ArticleCategory = ''' + #ArticleCategory + ''''
EXEC sys.sp_executesql #SQL
SELECT #RecordCount = COUNT(*)
FROM ##ResultSet
SELECT *
FROM ##ResultSet
WHERE RowNumber BETWEEN (#PageIndex - 1) * #PageSize + 1 AND (((#PageIndex - 1) * #PageSize + 1) + #PageSize) - 1
END
create a table which will hold all the table names to be processed and loop through this table inside your sproc.

Resources