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
Related
this query takes a lot of time running.
Does anyone know anyway to put them faster?
DECLARE #actual as INT
DECLARE #expected as INT
DECLARE #ID as INT
DECLARE #TSQL varchar(100)
DECLARE #t table (c int)
DECLARE #Id_aux varchar(100)
SET #ID = (select max(id) from [STG].table where fk_country = 5 )
SET #Id_aux= CONVERT(NVARCHAR(100), #ID)
SET #TSQL = 'SELECT * FROM OPENQUERY([MA],''select count(*) from table where id <=' + #Id_aux + ''')'
INSERT INTO #t EXEC (#TSQL)
SET #expected = (select c from #t)
SET #actual = (SELECT count(*) from [STG].table where fk_country = 5 and id<=#ID)
select #expected
select #actual
Thanks
It is better to use a different approach while executing queries via linked servers.
EXECUTE ... AT [Linked_Server];
Benefits:
This way a query will be executed on the remote server. Guaranteed. Thus it will be much more performant.
Very easy to pass parameters. No strings concatenation.
Useful link: SQL Server: Execute At LinkedServer
Check it out below.
SQL
DECLARE #actual as INT;
DECLARE #expected as INT;
DECLARE #ID as INT;
DECLARE #TSQL varchar(100);
DECLARE #t table (c int);
--DECLARE #Id_aux varchar(100);
SET #ID = (select max(id) from [PAY_STG].pay.paybuddy_purchase_ex where fk_country = 5 );
--SET #Id_aux= CONVERT(NVARCHAR(100), #ID);
--SET #TSQL = 'SELECT *
-- FROM OPENQUERY([BE_PAY_MA],
-- ''SELECT COUNT(*) FROM paybuddy_purchase_ex WHERE id <=' + #Id_aux + ''')';
--INSERT INTO #t EXEC (#TSQL);
INSERT INTO #t
EXECUTE(N'SELECT COUNT(*) FROM paybuddy_purchase_ex WHERE id <= ?',
#ID) AT [BE_PAY_MA];
SET #expected = (select c from #t);
SET #actual = (SELECT count(*) from [PAY_STG].pay.paybuddy_purchase_ex where fk_country = 5 and id<=#ID);
select #expected;
select #actual;
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'm using a while loop to iterate through some tables and carry out a replace on a field, to remove all the hyphens. All of the fields are varchar.
DECLARE #Table TABLE (TableName VARCHAR(max),Id int identity(1,1))
INSERT INTO #Table
Select distinct table_name From INFORMATION_SCHEMA.COLUMNS
DECLARE #max int
DECLARE #SQL VARCHAR(max)
DECLARE #TableName VARCHAR(max)
DECLARE #id int = 1
select #max = MAX(Id) from #Table
WHILE (#id <= #max)
BEGIN
SELECT #TableName = TableName FROM #Table WHERE Id = #id
SET #SQL = 'update '+ #TableName +' set colA = replace(colA,'-','');'
EXEC(#SQL)
SET #id = #id +1
END
the error I receive is:
The data types varchar(max) and varchar are incompatible in the subtract operator.
I've tried changing the varchar variables to fixed lengths or all to max, but nothing seems to work.
You need to use two single quotes when creating a single quote inside of a string:
DECLARE #Table TABLE (TableName VARCHAR(max),Id int identity(1,1))
INSERT INTO #Table
Select distinct table_name From INFORMATION_SCHEMA.COLUMNS
DECLARE #max int
DECLARE #SQL VARCHAR(max)
DECLARE #TableName VARCHAR(max)
DECLARE #id int = 1
select #max = MAX(Id) from #Table
WHILE (#id <= #max)
BEGIN
SELECT #TableName = TableName FROM #Table WHERE Id = #id
SET #SQL = 'update '+ #TableName +' set colA = replace(colA,''-'','''');'
EXEC(#SQL)
SET #id = #id +1
END
I get returned NULL when I execute this piece of code. Can you help me understand what is wrong with it? It's basically used to count rows in a table using a dynamic sql statement. Many thanks in advance.
DECLARE #sql nvarchar(4000),
#code nvarchar(40),
#count int,
#params nvarchar(4000)
SELECT #sql = N' SELECT #cnt = COUNT(*) FROM [Table1] WHERE [Column1]='''+quotename(#code)
SELECT #params = N'#code nvarchar(40), ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, 'AD', #cnt = #count OUTPUT
SELECT #count as x
select #sql as y
Let me know please if you need additional details. Appreciate the pointers/help on this. PS. I have tested this manually and the count is more than 1.
It is a good practise to pass arguments (#code) as params to sp_executesql:
CREATE TABLE #Table1 (Column1 NVARCHAR(100));
INSERT INTO #Table1(Column1) VALUES ('AD'), ('AD');
DECLARE #sql NVARCHAR(MAX),
#code NVARCHAR(40),
#count INT,
#params NVARCHAR(4000);
SELECT #sql = N'SELECT #cnt = COUNT(*)
FROM #Table1
WHERE [Column1]= #code;'
,#params = N'#code NVARCHAR(40),
#cnt INT OUTPUT';
EXEC [dbo].[sp_executesql]
#sql
,#params
,#code = 'AD'
,#cnt = #count OUTPUT;
SELECT #count AS x;
LiveDemo
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.