I have stored Procedure for Search.
ALTER Proc [dbo].[USP_GETFAQ]
#SortBy Varchar(128)='CreatedDate DESC',
#Page int=1,
#RecsPerPage int =10,
#Status Char(5)='',
#Question varchar(500)='',
#Answer varchar(1000)=''
As
DECLARE #SQL VARCHAR(MAX)
DECLARE #DSQL VARCHAR(MAX)
DECLARE #whereCondition VARCHAR(1024)
DECLARE #FirstRec int, #LastRec int
SET #FirstRec = (#Page - 1) * #RecsPerPage
SET #LastRec = (#Page * #RecsPerPage + 1)
Declare #SectionCount int;
Set NoCount On
Begin
SET #SQL='Select
ROW_NUMBER() over( order by '+#SortBy +') rownum,
* FROM faq where Status <>''D'''
if #Status !='' and #Status is not null AND #Status!='ALL'
begin
SET #SQL+=' AND Status = '''+#Status+''''
end
if #Question!=''
begin
SET #SQL +=' AND Question like '''+'%'+REPLACE(#Question, '''', '')+'%'+''''
end
if #Answer!=''
begin
SET #SQL +=' AND Answer like '''+'%'+REPLACE(#Answer, '''', '')+'%'+''''
end
SET #DSQL='SELECT * from (' + #SQL +') AS tbl'
print #DSQL
DECLARE #TEMPResult TABLE(RowNum INT,
ID uniqueIdentifier,
Question varchar(500),
Answer varchar(1000),
CreatedDate DateTime,
LastModifiedDate dateTime,
CreatedByIp varchar(20),
LastModifiedByIp varchar(20),
CreatedBy varchar(50),
ModifiedBy varchar(50),
[Order] int,
Status char(5)
)
INSERT INTO #TEMPResult EXEC(#DSQL)
SELECT (Select Count(*) from #TEMPResult) as Count,ID,SUBSTRING(question, 1, 200)question ,SUBSTRING(Answer, 1,250)Answer,
CreatedDate,LastModifiedDate,CreatedByIp ,LastModifiedByIp,CreatedBy,ModifiedBy, [Order], Status FROM #TEMPResult WHERE RowNum > #FirstRec AND RowNum < #LastRec
RETURN
End
When a question or answer contains "'" i getting error. that synatx is wrong near "'".
What i have tried so far is:
i have replaced the "'" with "''''" before passing the string to stored proc. it run successfully but not returning any record, please help me how can i do it.
Your method will lead to sql injection
MSDN SQL injection
Try to use EXEC sp_executesql #SQLString, #ParamDef, #paramList ...
MSDN sp_executesql
Your code:
ALTER Proc [dbo].[USP_GETFAQ]
#SortBy Varchar(128)='CreatedDate DESC',
#Page int=1,
#RecsPerPage int =10,
#Status Char(5)='',
#Question varchar(500)='',
#Answer varchar(1000)=''
As
DECLARE #SQL NVARCHAR(MAX)
DECLARE #FirstRec int, #LastRec int
SET #FirstRec = (#Page - 1) * #RecsPerPage
SET #LastRec = (#Page * #RecsPerPage + 1)
Declare #SectionCount int;
Set NoCount On
Begin
SET #SQL='SELECT * from (
Select ROW_NUMBER() over( order by '+#SortBy +') rownum,
* FROM faq where Status <>''D'''
if #Status !='' and #Status is not null AND #Status!='ALL'
begin
SET #SQL+=' AND Status = #Status '
end
if #Question!=''
begin
SET #Question = '%'+#Question+'%'
SET #SQL +=' AND Question like #Question'
end
if #Answer!=''
begin
SET #Answer = '%'+#Answer+'%'
SET #SQL +=' AND Answer like #Answer'
end
SET #SQL += ') AS tbl'
print #SQL
DECLARE #ParamDefinition nvarchar(4000)
SET #ParamDefinition =
'#Status Char(5),
#Question varchar(500),
#Answer varchar(1000)';
DECLARE #TEMPResult TABLE(RowNum INT,
ID uniqueIdentifier,
Question varchar(500),
Answer varchar(1000),
CreatedDate DateTime,
LastModifiedDate dateTime,
CreatedByIp varchar(20),
LastModifiedByIp varchar(20),
CreatedBy varchar(50),
ModifiedBy varchar(50),
[Order] int,
Status char(5)
)
INSERT INTO #TEMPResult
EXECUTE sp_executesql #SQL, #ParamDefinition
,#Status = #Status
,#Question = #Question
,#Answer = #Answer
SELECT (Select Count(*) from #TEMPResult) as Count,ID,SUBSTRING(question, 1, 200)question ,SUBSTRING(Answer, 1,250)Answer,
CreatedDate,LastModifiedDate,CreatedByIp ,LastModifiedByIp,CreatedBy,ModifiedBy, [Order], Status FROM #TEMPResult WHERE RowNum > #FirstRec AND RowNum < #LastRec
RETURN
End
Use 3 single quotes in a row. Like '''. Do not use any double quotes.
Related
I am trying to write a query that needs to call a stored procedure. But it always throws an error:
Unknown object type 'TABLEIXICHistoricalData' used in a CREATE, DROP, or ALTER statement.
This is query:
USE ETLCourse
DECLARE #LOOP TABLE
(
ID INT IDENTITY(1,1),
TableName NVARCHAR(100)
)
INSERT INTO #LOOP (TableName)
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '%_Stocks%'
DECLARE #b INT = 1, #m INT, #t NVARCHAR(100)
SELECT #m = MAX(ID) FROM #LOOP
WHILE #b <= #m
BEGIN
SELECT #t = TableName
FROM #LOOP
WHERE ID = #b
EXECUTE [dbo].[stp_BuildNormalizedTable] #t
SET #b = #b + 1
END
and here is the procedure:
ALTER PROCEDURE [dbo].[stp_BuildNormalizedTable]
#table NVARCHAR(100)
AS
BEGIN
DECLARE #cleanTable NVARCHAR(100),
#s NVARCHAR(MAX)
SET #cleanTable = REPLACE(#table, '_Stocks', 'HistoricalData')
SET #s = 'CREATE TABLE' + #cleanTable + '(ID INT IDENTITY(1,1), Price DECIMAL(13, 4), PriceDate DATE)
INSERT INTO' + #cleanTable + '(Price,PriceDate) SELECT [Adj Close],[Date] FROM'
+ #table + ' ORDER BY Date ASC'
--PRINT #s
EXECUTE sp_executesql #s
END
It should copy two specific column and create a new table by using #Loop table and procedure
You need to add 'space' after 'create table' and 'insert into' and 'from'
declare #s nvarchar(max)
declare #cleantable nvarchar(100)
declare #table nvarchar(100)
set #cleantable = 'aaa'
set #table = 'bbb'
SET #s = 'CREATE TABLE' + #cleanTable + '(ID INT IDENTITY(1,1),Price Decimal(13,4),PriceDate DATE)
Insert into' + #cleanTable
+ '(Price,PriceDate) SELECT [Adj Close],[Date] FROM'
+ #table + ' ORDER BY Date ASC'
print #s
Output:
CREATE TABLEaaa(ID INT IDENTITY(1,1),Price Decimal(13,4),PriceDate DATE)
Insert intoaaa(Price,PriceDate) SELECT [Adj Close],[Date] FROMbbb ORDER BY Date ASC
Use 'print' to check your query.
I broke this query down to the most basic. I need to add an OR statement dynamically, which includes a variable. I need to get any id and its corresponding id with an underscore. So, my resulting #SQL to execute would be:
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
--
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
SET #SQL = #SQL + ' AND OrigID in (''' + #OriginId + ''') '
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = '_%'
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10))) + #Origin
SET #SQL_2 = N' OR OrigID LIKE ''' + #Origin + ''' '
SET #SQL_2 = #SQL + #SQL_2
print(#SQL_2)
SET #counter = #counter + 1
END
EXEC sp_executesql #SQL_2,#ParamDefinition,#OrganizationId,#OriginId
drop table #inVars
drop table #Test
Here is how my query is executing now:
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '31_%'
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '33_%'
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '25_%'
This is my desired result:
SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId AND OrigID in ('31,25,33') OR OrigID LIKE '31_%'
OR OrigID LIKE '33_%'
OR OrigID LIKE '25_%'
A few problems: You can't concatenate a NULL with a string EVER; the result is always NULL (please look at the IF #Origin IS NOT NULL line). In your loop, you should be updating #SQL, not #SQL_2. Lastly, you should wrap ORs in parens so the logic is always explicit.
SET NOCOUNT ON
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
SET #SQL = #SQL + ' AND (OrigID in (''' + #OriginId + ''') '
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = '_%'
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10))) + #Origin
IF #Origin IS NOT NULL
BEGIN
SET #SQL_2 = N' OR OrigID LIKE ''' + #Origin + ''' '
SET #SQL = #SQL + #SQL_2
END
SET #counter = #counter + 1
END
SET #SQL=#SQL+')'
print #SQL
drop table #inVars
drop table #Test
It is not very clear what you want here but I think you are making it harder on yourself than you need to. There is no need to use the IN because you are also finding all values that begin with the same value. And you have hard coded the same values into your temp table. Using a string splitter this is about a million times less complicated. Just split your #OriginID on the commas and use LIKE in the join.
I am using the DelimitedSplit8k which you can find here
I am pretty sure this should get you the information you are looking for. I would recommend avoiding loops whenever possible.
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
select *
from #Test t
join DelimitedSplit8K(#OriginID, ',') x on t.OrigID like x.Item + '%'
drop table #Test
I solved this.Thanks all who replied.
create table #Test (OrganizationId varchar(100), OrigID varchar(50))
insert into #Test(OrganizationId,OrigID)
Values ('5','31'),
('5','31_00000'),
('5','33'),
('5','33_00000'),
('5','25'),
('5','25_00000'),
('5','HD_00000'),
('5','HD')
DECLARE
#OrganizationId int = 5,
#OriginId nvarchar(256) = N'31,25,33'
create table #inVars(id int NOT NULL IDENTITY PRIMARY KEY, origins varchar(256))
insert into #inVars(origins)
Values ('31'),
('33'),
('25')
DECLARE #SQL NVARCHAR(MAX),
#ParamDefinition NVARCHAR(MAX)
SET #ParamDefinition = N'#OrganizationId int,
#OriginId nvarchar(256)'
SET #SQL= 'SELECT OrganizationId,OrigID
FROM #Test
WHERE OrganizationId=#OrganizationId'
IF ISNULL(#OriginId,'') <> ''
BEGIN
SET #SQL = #SQL +' AND (OrigID in (''' + #OriginId + ''')) '
END
IF ISNULL(#OriginId,'') <> ''
DECLARE #counter INT = 1, #max INT = 0, #Origin nvarchar(50), #SQL_2 nvarchar(max)
SELECT #max = COUNT(id) FROM #inVars
WHILE #counter <= #max
BEGIN
SET #Origin = (select origins from #invars where id = CAST(#counter as varchar(10)))
SET #Origin = #Origin+'_%'
SET #SQL_2 = N' OR (OrigID LIKE ''' + #Origin + ''') '
SET #SQL = #SQL + #SQL_2
SET #counter = #counter + 1
END
print(#SQL)
EXEC sp_executesql #SQL,#ParamDefinition,#OrganizationId,#OriginId
drop table #inVars
drop table #Test
I am inserting records using stored procedure and sp_executesql. Once I insert record using sp_executesql, i need the last inserted identity field value on that session.
ALTER proc [dbo].[spHoldTransaction]
#RegisterNo int,
#StoreID int,
#Department varchar(50),
#TransactionDateFrom date,
#TransactionDateTo date,
#Comment Varchar(50)
AS
BEGIN
DECLARE #RegisterID int;
DECLARE #DatabaseName varchar(15);
DECLARE #Batch int;
SELECT #RegisterID=ID FROM Register WHERE Register.Number = #RegisterNo;
SELECT #Batch = BatchNumber From Batch WHERE Status = 0 and RegisterID = #RegisterID
SET #DatabaseName = 'xxx'
SELECT #Department=''''+REPLACE(#Department,',',''',''')+''''
DECLARE #Qry nvarchar(MAX);
DECLARE #ParamDefinition nvarchar(MAX);
SET #ParamDefinition = N'#comment nvarchar(50),#StoreID int,#Batch int'
SET #Qry = '
INSERT INTO '+#DatabaseName+'.dbo.TransactionHold
(
[StoreID]
,[HoldComment]
,[BatchNumber]
,[ShippingNotes]
)
SELECT
#StoreID AS [StoreID]
,#Comment AS [HoldComment]
,#Batch AS [BatchNumber]
,'''' AS [ShippingNotes];
'
EXECUTE sp_executesql #Qry, #ParamDefinition, #Comment, #StoreID, #Batch
SELECT SCOPE_IDENTITY()
END
When I execute this above stored procedure, it's return empty. But TransactionHold has identity column Id
Try retrieving the identity inside the same scope of the execute sql procedure and return the value as an OUT parameter. Do these changes:
SET #ParamDefinition = N'#comment nvarchar(50),#StoreID int,#Batch int, #identity int out'
SET #Qry = '
INSERT INTO '+#DatabaseName+'.dbo.TransactionHold
(
[StoreID]
,[HoldComment]
,[BatchNumber]
,[ShippingNotes]
)
SELECT
#StoreID AS [StoreID]
,#Comment AS [HoldComment]
,#Batch AS [BatchNumber]
,'''' AS [ShippingNotes];
SET #identity = ##IDENTITY
'
DECLARE #identity INT
EXECUTE sp_executesql #Qry, #ParamDefinition, #Comment, #StoreID, #Batch, #identity OUT
SELECT #identity
I would like to add the following stored procedure to all existing databases which contain the table schichten. All my approaches have failed so I'm looking for help here.
This is my approach:
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
CREATE PROCEDURE #currentDb.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = 'konz'
BEGIN
SET #ASSelector = 'Taxi'
SET #IFPers=''
END
ELSE
BEGIN
SET #ASSelector = 'Personal'
SET #IFPers = '[name] AS Name,'
END
SET #sql1 = N';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL(['+ #Selector +'],0) AS '+ #ASSelector +','+ #IFPers +'
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN ('+ #ColumnName + N' )) AS UMSAETZE )
SELECT *, '+ #Gesamtergebnis +' AS Gesamtergebnis FROM temp ORDER BY '+ #ASSelector +''
EXEC sp_executesql #sql
END
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
I am hoping that there is someone who can help me.
You have to execute the create procedure separately, so if you wrap it up into a variable and use exec sp_executesql it should work.
IF object_id('tempdb.dbo.#database') is not null
drop TABLE #database
GO
CREATE TABLE #database(id INT identity primary key, name sysname)
GO
SET NOCOUNT ON
INSERT INTO #database(name)
SELECT name
FROM sys.databases
WHERE source_database_id is null
ORDER BY name
SELECT * FROM #database
DECLARE #id INT, #cnt INT, #sql NVARCHAR(MAX), #currentDb SYSNAME;
SELECT #id = 1, #cnt = max(id) FROM #database
WHILE #id <= #cnt
BEGIN
BEGIN TRY
SELECT #currentDb = name
FROM #database
WHERE id = #id
IF OBJECT_ID(#currentDb+'.dbo.schichten') IS NOT NULL
begin
set #sql = 'CREATE PROCEDURE '+#currentDb+'.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END'
EXEC sp_executesql #sql
END TRY
BEGIN CATCH
END CATCH
SET #id = #id + 1;
END
GO
Assuming this is a one time need as opposed to a nightly maintenance task, you can use a built-in stored procedure, sys.sp_MSforeachdb, to execute a statement in each database. It is safe to use and has been discussed extensively on the web. However, it is an undocumented feature and can be removed without notice by Microsoft so you don't want to depend on it for recurring tasks.
Create and validate your statement in one database, then use this stored procedure to execute it in all of the databases. ? is the placeholder for the database name.
EXEC sys.sp_MSforeachdb #command1 =
'IF OBJECT_ID(''?.dbo.schichten'') IS NOT NULL
AND OBJECT_id(''?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]'') IS NOT NULL
BEGIN
CREATE PROCEDURE ?.[dbo].[Ausw_Tabelle_Taxi_Pers_Jahr]
#ColumnName nvarchar(MAX),
#Selector nvarchar(MAX),
#Gesamtergebnis nvarchar(MAX)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql1 AS NVARCHAR(MAX),
#ASSelector nvarchar(MAX),
#IFPers nvarchar(MAX);
IF #Selector = ''konz''
BEGIN
SET #ASSelector = ''Taxi''
SET #IFPers=''''
END
ELSE
BEGIN
SET #ASSelector = ''Personal''
SET #IFPers = ''[name] AS Name,''
END
SET #sql1 = N'';WITH temp AS (SELECT *
FROM (
SELECT
ISNULL((DATENAME(m,[datum])+ cast(datepart(yyyy,[datum]) as varchar(5))),0) AS MONTHYEAR,
ISNULL([''+ #Selector +''],0) AS ''+ #ASSelector +'',''+ #IFPers +''
ISNULL((ISNULL([umsum],0) +
ISNULL([sonst_0],0) +
ISNULL([sonst_7],0) +
ISNULL([sonst_16],0) +
ISNULL([sonst_z],0) -
ISNULL([ff],0)),0) AS UMSATZSUMME
FROM [dbo].[schichten]
) AS SOURCE
PIVOT (SUM([UMSATZSUMME]) FOR [MONTHYEAR] IN (''+ #ColumnName + N'' )) AS UMSAETZE )
SELECT *, ''+ #Gesamtergebnis +'' AS Gesamtergebnis FROM temp ORDER BY ''+ #ASSelector +''''
EXEC sp_executesql #sql1
END
'
Trying to create a Stored procedure that will give the required no. of records and also the total no. of records in that table.
The '#Query' part gives result when I execute it separately. So there's no problem with that.
Could Someone please check if the syntax is correct, cause I'm not getting at any result.
ALTER PROCEDURE GetRecordsByPage
(
#TableName nvarchar(50),
#ColumnName nvarchar(50),
#OrderByClause nvarchar(50),
#StartIndex nvarchar(50),
#EndIndex nvarchar(50),
#TotalRows nvarchar(50) output
)
AS
BEGIN
DECLARE #Query nvarchar(max)
select #Query = 'select '+#TotalRows+' = count(*) from '+#TableName+'
where deleted=0
with temp as (select row_number() over (order by '+
#colname+' '+#OrderByClause+') as row, * from '+#tablename+')
select * from temp where row between '+#startIndex+' and '
+#EndIndex
execute sp_executesql #Query, #TotalRows output
END
--is this correct, to test this stored procedure
-- execute GetRecordsByPage 'tblBranch','BranchName', '2', '10'
Otherwise, the queries would be:
select count(*) from tblBranch;
With temp as
(select row_number over(order by name desc) as row, * from tblbranch)
select * from temp where row between 11 and 20;
ALTER PROCEDURE GetRecordsByPage
(
#TableName nvarchar(50),
#ColumnName nvarchar(50),
#OrderByClause nvarchar(50),
#StartIndex nvarchar(50),
#EndIndex nvarchar(50),
#TotalRows nvarchar(50) output
)
AS
BEGIN
DECLARE #Query nvarchar(max)
select #Query = 'select #TotalRowsOut = count(*) from '+#TableName+'
where deleted=0
with temp as (select row_number() over (order by '+
#colname+' '+#OrderByClause+') as row, * from '+#tablename+')
select * from temp where row between '+#startIndex+' and '
+#EndIndex
DECLARE #ParmDefinition nvarchar(500);
SET #ParmDefinition = N'#TotalRowsOut int OUTPUT';
execute sp_executesql #Query, #ParmDefinition,#TotalRowsOut=#TotalRows output
select #TotalRows
END