I am getting Dollar sign unterminated - postgresql

I want to create a function like below which inserts data as per the input given. But I keep on getting an error about undetermined dollar sign.
CREATE OR REPLACE FUNCTION test_generate
(
ref REFCURSOR,
_id INTEGER
)
RETURNS refcursor AS $$
DECLARE
BEGIN
DROP TABLE IF EXISTS test_1;
CREATE TEMP TABLE test_1
(
id int,
request_id int,
code text
);
IF _id IS NULL THEN
INSERT INTO test_1
SELECT
rd.id,
r.id,
rd.code
FROM
test_2 r
INNER JOIN
raw_table rd
ON
rd.test_2_id = r.id
LEFT JOIN
observe_test o
ON
o.raw_table_id = rd.id
WHERE o.id IS NULL
AND COALESCE(rd.processed, 0) = 0;
ELSE
INSERT INTO test_1
SELECT
rd.id,
r.id,
rd.code
FROM
test_2 r
INNER JOIN
raw_table rd
ON rd.test_2_id = r.id
WHERE r.id = _id;
END IF;
DROP TABLE IF EXISTS tmp_test_2_error;
CREATE TEMP TABLE tmp_test_2_error
(
raw_table_id int,
test_2_id int,
error text,
record_num int
);
INSERT INTO tmp_test_2_error
(
raw_table_id,
test_2_id,
error,
record_num
)
SELECT DISTINCT
test_1.id,
test_1.test_2_id,
'Error found ' || test_1.code,
0
FROM
test_1
WHERE 1 = 1
AND data_origin.id IS NULL;
INSERT INTO tmp_test_2_error
SELECT DISTINCT
test_1.id,
test_1.test_2_id,
'Error found ' || test_1.code,
0
FROM
test_1
INNER JOIN
data_origin
ON
data_origin.code = test_1.code
WHERE dop.id IS NULL;
DROP table IF EXISTS test_latest;
CREATE TEMP TABLE test_latest AS SELECT * FROM observe_test WHERE 1 = 2;
INSERT INTO test_latest
(
raw_table_id,
series_id,
timestamp
)
SELECT
test_1.id,
ds.id AS series_id,
now()
FROM
test_1
INNER JOIN data_origin ON data_origin.code = test_1.code
LEFT JOIN
observe_test o ON o.raw_table_id = test_1.id
WHERE o.id IS NULL;
CREATE TABLE latest_observe_test as Select * from test_latest where 1=0;
INSERT INTO latest_observe_test
(
raw_table_id,
series_id,
timestamp,
time
)
SELECT
t.id,
ds.id AS series_id,
now(),
t.time
FROM
test_latest t
WHERE t.series_id IS DISTINCT FROM observe_test.series_id;
DELETE FROM test_2_error re
USING t
WHERE t.test_2_id = re.test_2_id;
INSERT INTO test_2_error (test_2_id, error, record_num)
SELECT DISTINCT test_2_id, error, record_num FROM tmp_test_2_error ORDER BY error;
UPDATE raw_table AS rd1
SET processed = case WHEN tre.raw_table_id IS null THEN 2 ELSE 1 END
FROM test_1 tr
LEFT JOIN
tmp_test_2_error tre ON tre.raw_table_id = tr.id
WHERE rd1.id = tr.id;
OPEN ref FOR
SELECT 1;
RETURN ref;
OPEN ref for
SELECT o.* from observe_test o
;
RETURN ref;
OPEN ref FOR
SELECT
rd.id,
ds.id AS series_id,
now() AS timestamp,
rd.time
FROM test_2 r
INNER JOIN raw_table rd ON rd.test_2_id = r.id
INNER JOIN data_origin ON data_origin.code = rd.code
WHERE o.id IS NULL AND r.id = _id;
RETURN ref;
END;
$$ LANGUAGE plpgsql VOLATILE COST 100;
I am not able to run this procedure.
Can you please help me where I have done wrong?

I am using squirrel and face the same question as you.
until I found that:
-- Note that if you want to create the function under Squirrel SQL,
-- you must go to Sessions->Session Properties
-- then SQL tab and change the Statement Separator from ';' to something else
-- (for intance //). Otherwise Squirrel SQL sends one piece to the server
-- that stops at the first encountered ';', and the server cannot make
-- sense of it. With the separator changed as suggested, you type everything
-- as above and end with
-- ...
-- end;
-- $$ language plpgsql
-- //
--
-- You can then restore the default separator, or use the new one for
-- all queries ...
--

Related

PgSQL function returning table and extra data computed in process

In PgSQL I make huge select, and then I want count it's size and apply some extra filters.
execute it twice sound dumm,
so I wrapped it in function
and then "cache" it and return union of filtered table and extra row at the end where in "id" column store size
with q as (select * from myFunc())
select * from q
where q.distance < 400
union all
select count(*) as id, null,null,null
from q
but it also doesn't look like proper solution...
and so the question: is in pg something like "generator function" or any other stuff that can properly solve this ?
postgreSQL 13
myFunc aka "selectItemsByRootTag"
CREATE OR REPLACE FUNCTION selectItemsByRootTag(
in tag_name VARCHAR(50)
)
RETURNS table(
id BIGINT,
name VARCHAR(50),
description TEXT,
/*info JSON,*/
distance INTEGER
)
AS $$
BEGIN
RETURN QUERY(
WITH RECURSIVE prod AS (
SELECT
tags.name, tags.id, tags.parent_tags
FROM
tags
WHERE tags.name = (tags_name)
UNION
SELECT c.name, c.id , c.parent_tags
FROM
tags as c
INNER JOIN prod as p
ON c.parent_tags = p.id
)
SELECT
points.id,
points.name,
points.description,
/*points.info,*/
points.distance
from points
left join tags on points.tag_id = tags.id
where tags.name in (select prod.name from prod)
);
END;
$$ LANGUAGE plpgsql;
as a result i want see maybe set of 2 table or generator function that yield some intermediate result not shure how exacltly it should look
demo
CREATE OR REPLACE FUNCTION pg_temp.selectitemsbyroottag(tag_name text, _distance numeric)
RETURNS TABLE(id bigint, name text, description text, distance numeric, count bigint)
LANGUAGE plpgsql
AS $function$
DECLARE _sql text;
BEGIN
_sql := $p1$WITH RECURSIVE prod AS (
SELECT
tags.name, tags.id, tags.parent_tags
FROM
tags
WHERE tags.name ilike '%$p1$ || tag_name || $p2$%'
UNION
SELECT c.name, c.id , c.parent_tags
FROM
tags as c
INNER JOIN prod as p
ON c.parent_tags = p.id
)
SELECT
points.id,
points.name,
points.description,
points.distance,
count(*) over ()
from points
left join tags on points.tag_id = tags.id
where tags.name in (select prod.name from prod)
and points.distance > $p2$ || _distance
;
raise notice '_sql: %', _sql;
return query execute _sql;
END;
$function$
You can call it throug following way
select * from pg_temp.selectItemsByRootTag('test',20);
select * from pg_temp.selectItemsByRootTag('test_8',20) with ORDINALITY;
The 1 way to call the function, will have a row of total count total number of rows. Second way call have number of rows plus a serial incremental number.
I also make where q.distance < 400 into function input argument.
selectItemsByRootTag('test',20); means that q.distance > 20 and tags.name ilike '%test%'.

Issue with PK violation on insert

I have a scenario where almost all of the tables have issues with the PK value as follows. This results is a database error or the violation of the PK insert.
When using the DBCC CheckIdent it displays an inconsistency between the next value and the current one.
Can anyone have a reason for the mismatch happening on several tables?
Since this database is then replicate, I'm afraid this error will propagate across the environment.
I adapted this script to fix it, but really trying to figure out the root of the problem.
/** Version 3.0 **/
if object_id('tempdb..#temp') is not null
drop table #temp
;
with cte as (
SELECT
distinct
A.TABLE_CATALOG AS CATALOG,
A.TABLE_SCHEMA AS "SCHEMA",
A.TABLE_NAME AS "TABLE",
B.COLUMN_NAME AS "COLUMN",
IDENT_SEED (A.TABLE_NAME) AS Seed,
IDENT_INCR (A.TABLE_NAME) AS Increment,
IDENT_CURRENT (A.TABLE_NAME) AS Curr_Value
, DBPS.row_count AS NumberOfRows
FROM INFORMATION_SCHEMA.TABLES A
inner join INFORMATION_SCHEMA.COLUMNS B on b.TABLE_NAME = a.TABLE_NAME and b.TABLE_SCHEMA = a.TABLE_SCHEMA
inner join sys.identity_columns IC on OBJECT_NAME (IC.object_id) = a.TABLE_NAME
inner join sys.dm_db_partition_stats DBPS ON DBPS.object_id =IC.object_id
inner join sys.indexes as IDX ON DBPS.index_id =IDX.index_id
WHERE A.TABLE_CATALOG = B.TABLE_CATALOG AND
A.TABLE_SCHEMA = B.TABLE_SCHEMA AND
A.TABLE_NAME = B.TABLE_NAME AND
COLUMNPROPERTY (OBJECT_ID (B.TABLE_NAME), B.COLUMN_NAME, 'IsIdentity') = 1 AND
OBJECTPROPERTY (OBJECT_ID (A.TABLE_NAME), 'TableHasIdentity') = 1 AND
A.TABLE_TYPE = 'BASE TABLE'
)
select 'DBCC CHECKIDENT ('''+A.[SCHEMA]+'.'+a.[TABLE]+''', reseed)' command
, ROW_NUMBER() OVER(ORDER BY a.[SCHEMA], a.[TABLE] asc) AS ID
, A.Curr_Value
, a.[TABLE]
into #temp
from cte A
ORDER BY A.[SCHEMA], A.[TABLE]
declare #i int = 1, #count int = (select max(ID) from #temp)
declare #text varchar(max) = ''
select #COUNT= count(1) FROM #temp
WHILE #I <= #COUNT
BEGIN
SET #text = (SELECT command from #temp where ID=#I)
EXEC (#text + ';')
print #text
select Curr_Value OldValue, ident_current([TABLE]) FixValue, [TABLE] from #temp where ID=#I
SET #I = #I + 1
SET #text='';
END
go
maybe someone or something with enough permissions made a mistake by reseeding?
As simple as this:
create table testid (
id int not null identity (1,1) primary key,
data varchar (3)
)
insert into testid (data) values ('abc'),('cde')
DBCC CHECKIDENT ('testid', RESEED, 1)
insert into testid (data) values ('bad')

How can I use sp_spaceused on specific tables?

I'm trying to call sp_spaceused to get the number of rows in a few specific tables that I want to monitor, but I'm trying to avoid using a cursor.
I've made a table to hold all the tables I want to monitor:
CREATE TABLE MonitoredTable
(
MonitoredTableID INT PRIMARY KEY IDENTITY(1, 1) NOT NULL
, DatabaseName NVARCHAR(128) NOT NULL
, SchemaName NVARCHAR(128) NOT NULL
, TableName NVARCHAR(128) NOT NULL
, RowNumberThreshold INT NOT NULL
, IsActive BIT NOT NULL
)
My problem is: I want to create a function that will only return MonitoredTableIDs for tables that their row counts exceed the defined RowNumberThreshold.
Here's what I'd like to do, but this is invalid SQL:
CREATE FUNCTION dbo.GetTablesLargerThanThreshold()
RETURNS #tablesLargerThanThreshold TABLE
(
MonitoredTableID INT NOT NULL
)
AS
BEGIN
INSERT INTO #tablesLargerThanThreshold
SELECT MonitoredTableID
FROM MonitoredTable
WHERE IsActive = 1
AND (SELECT [rows] FROM (EXEC sp_spaceused DatabaseName + '.' + SchemaName + '.' + TableName)) > RowNumberThreshold
RETURN
END
Is there a way I can check if the number of rows in a MonitoredTable are greater than the defined RowNumberThreshold without resorting to a cursor?
Something like this?
-- See the following pages for documentation on the tables used in this query:
--
-- sys.indexes https://msdn.microsoft.com/en-us/library/ms173760.aspx
-- sys.partitions https://msdn.microsoft.com/en-us/library/ms175012.aspx
-- sys.allocation_units https://msdn.microsoft.com/en-us/library/ms189792.aspx
-- sys.tables Only columns inherited from sys.object, see link below
-- sys.object https://msdn.microsoft.com/en-us/library/ms190324.aspx
SELECT OBJECT_NAME(i.OBJECT_ID) AS [TableName]
, p.[rows] AS [Num_Rows]
FROM sys.indexes AS i
INNER JOIN sys.partitions AS p
ON p.OBJECT_ID = i.OBJECT_ID
AND p.index_id = i.index_id
INNER JOIN sys.allocation_units AS a
ON a.container_id = p.partition_id
INNER JOIN sys.tables AS t
ON i.OBJECT_ID = t.OBJECT_ID
WHERE i.type <= 1 -- Heap or clustered index
AND a.type = 1 -- In-row data
AND t.type = 'U' -- User-defined table
AND t.is_ms_shipped = 0 -- sys.object was not created by an internal SQL Server component

Slow triggers checking primary key constraints with postgresql

I am trying to check primary key constraints along the inheritance tree in postgresql using a plpythonu trigger (check_pk). I'm using (PostgreSQL) 9.4.5.
My question is why does the insert or update take at least 50 ms, when the execution of the trigger itself takes at most 5 ms? Am I doing something wrong? Is there a way to improve this?
The code
(git#github.com:collorg/oopg.git)
The tables:
I'm testing with three tables parent, childb and childc (see bellow for the trigger):
create table parent(
a text primary key
);
create trigger check_pk
before insert or update on parent
for each row execute procedure check_pk();
create table childb(
b text,
primary key(a, b)
) inherits(parent);
create trigger check_pk
before insert or update on childb
for each row execute procedure check_pk();
create table childc(
c text,
primary key(a, c)
) inherits(parent);
create trigger check_pk
before insert or update on childc
for each row execute procedure check_pk();
The tests:
insert into parent (a) values ('a') -- OK
insert into childb (a, b) values ('a', 'a') -- FAILS
insert into childb (a, b) values ('b', 'a') -- OK
insert into parent (a) values ('b') -- FAILS
insert into parent (a) values ('b') -- FAILS
insert into childc (a, c) values ('b', 'a') -- FAILS
insert into childc (a, c) values ('c', 'a') -- OK
select * from parent -- a, b, c
update parent set a = 'b' -- FAILS
update childb set a = 'c' -- FAILS
update childb set a = 'd' -- OK
Here is an excerpt of the postgresql logs (I've set log_min_duration_statement to 10 ms in postgresql.conf):
======== get_pk_fields(59959)
check_pk_oid: SELECT a FROM public.parent WHERE a = 'c' limit 1
CLEF DUPLIQUEE
check_pk_oid duration: 0:00:00.003948
check_pk duration: 0:00:00.004504
2015-12-10 08:53:16 CET LOG: durée : 71.940 ms, instruction : update parent set a = 'c'
The update takes 71.940 ms when the execution of the check_pk trigger takes 4.5 ms.
The trigger:
create language plpythonu;
--
--
--
CREATE FUNCTION check_pk()
RETURNS trigger
AS $$
from datetime import datetime
from sys import stderr
begin = datetime.now()
oid = TD['relid']
GD['td'] = TD
ok = plpy.execute(
"SELECT check_pk_oid({})".format(oid))[0]['check_pk_oid']
stderr.write("check_pk duration: {}\n".format(datetime.now() - begin))
if not ok:
return 'SKIP'
$$ LANGUAGE plpythonu;
--
--
--
CREATE FUNCTION check_pk_oid(integer)
returns boolean
AS $$
"""Return False if the key is found in any of the parents."""
from datetime import datetime
from sys import stderr
from psycopg2.extensions import adapt
begin = datetime.now()
oid = args[0]
stderr.write("{} check_pk_oid({})\n".format(8*'=', oid))
TD = GD['td']
stderr.write("GD['td'] = {}\n".format(TD))
parent_oid = plpy.execute(
"SELECT get_inhparent('{}')".format(oid))[0]['get_inhparent']
stderr.write("oid du parent {}\n".format(parent_oid))
if parent_oid:
# recurse on parent_oid
query = ("SELECT check_pk_oid({})".format(parent_oid))
stderr.write("check uid request: {}\n".format(query))
return plpy.execute(query)[0]['check_pk_oid']
# Get the FQTN and the field names of the primary key
pk_infos = plpy.execute(
"SELECT get_pk_fields({})".format(oid))[0]['get_pk_fields']
fqtn, pk_fieldnames = pk_infos[0], pk_infos[1:]
if not pk_fieldnames:
stderr.write(
"check_pk_oid duration ok 1: {}\n".format(datetime.now() - begin))
return True
# Clause for the SELECT request
fields = []
clause = []
for field in pk_fieldnames:
fields.append(field)
if TD['new'][field] == 0:
valeur = 0
else:
valeur = TD['new'][field] or ""
valeur = adapt(valeur)
clause.append("{} = {}".format(field, str(valeur)))
# construction de la requête d''extraction
req = "SELECT {} FROM {} WHERE {} limit 1".format(
', '.join(fields), fqtn, ' and '.join(clause))
stderr.write("check_pk_oid: {}\n".format(req))
if len(plpy.execute(req)) == 1:
stderr.write("CLEF DUPLIQUEE\n")
stderr.write("check_pk_oid duration: {}\n".format(datetime.now() - begin))
return False
stderr.write("check_pk_oid duration ok 2: {}\n".format(datetime.now() - begin))
return True
$$ LANGUAGE plpythonu;
--
--
--
CREATE FUNCTION get_inhparent(integer)
RETURNS integer
AS $$
from sys import stderr
relid = args[0]
stderr.write("{} get_inhparent({})\n".format(8*'=', relid))
query = (
"SELECT inhparent FROM pg_catalog.pg_inherits WHERE inhrelid = {}".format(
relid))
stderr.write('get_inhparent: {}\n'.format(query))
rec = plpy.execute(query)
try:
return rec[0]['inhparent']
except:
return 0
$$ LANGUAGE plpythonu;
--
--
--
CREATE FUNCTION get_pk_fields(oid)
RETURNS varchar[]
AS $$
"""
Return the field names in the primary key
"""
from sys import stderr
oid = args[0]
stderr.write("{} get_pk_fields({})\n".format(8*'=', oid))
# rec_st : record contenant schemaname et relname
rec_st = plpy.execute(
"""SELECT schemaname, relname
FROM pg_catalog.pg_stat_all_tables
WHERE relid = {}""".format(oid))
schemaname = rec_st[0]['schemaname']
relname = rec_st[0]['relname']
l_fieldnames = plpy.execute(
"""
SELECT
a.attrelid AS tableid,
c.relkind AS tablekind,
n.nspname::varchar AS schemaname,
c.relname::varchar AS relationname,
array_agg(distinct i.inhparent) as parent,
array_agg(a.attname::varchar) AS fieldnames,
array_agg(a.attnum) as attnums,
array_agg(a.attislocal) AS local,
cn_pk.contype AS pkey
FROM
pg_class c -- table
LEFT JOIN pg_namespace n ON
c.relname = '{}' and
n.oid = c.relnamespace and
n.nspname = '{}'
LEFT JOIN pg_inherits i ON
i.inhrelid = c.oid
LEFT JOIN pg_attribute a ON
a.attrelid = c.oid
JOIN pg_type pt ON
a.atttypid = pt.oid
-- LEFT JOIN pg_constraint cn_uniq ON
-- cn_uniq.contype = 'u' AND
-- cn_uniq.conrelid = a.attrelid AND
-- a.attnum = ANY( cn_uniq.conkey )
JOIN pg_constraint cn_pk ON
cn_pk.contype = 'p' AND
cn_pk.conrelid = a.attrelid AND
a.attnum = ANY( cn_pk.conkey )
WHERE
n.nspname <> 'pg_catalog'::name AND
n.nspname <> 'information_schema'::name AND
( c.relkind = 'r'::"char" )
GROUP BY
a.attrelid,
c.relkind,
n.nspname,
c.relname,
cn_pk.contype""".format(relname, schemaname))[0]['fieldnames']
fqtn = "{}.{}".format(schemaname, relname)
return [fqtn] + l_fieldnames
fieldnames = ','.join(l_fieldnames)
resultat = fqtn + ":" + fieldnames
stderr.write("{}\n".format(resultat))
return resultat
$$ LANGUAGE plpythonu;
I've got my answer. plpython is great for prototyping but it comes with a cost. If I use this trigger which basically does nothing, the insert time is around 30 ms... So I guess I'll have to code that in C if I want better performances.
create language plpythonu;
CREATE OR REPLACE FUNCTION slow()
RETURNS trigger
AS $$
pass
$$ LANGUAGE plpythonu;
Note: the code posted here is obsolete and buggy (no multiple inheritance, ...) but it continues to evolve on https://github.com/collorg/oopg.

Establishing Upper / Lower Bound in T-SQL Procedure

I am trying to establish upper / lower bound in my stored procedure
below and am having some problems at the end (I am getting no results
where, without the temp table inner join i get the expected results).
I need some help where I am trying to join the columns in my temp table #PageIndexForUsers
to the rest of my join statement and I am mucking something up with
this statement:
INNER JOIN
#PageIndexForUsers ON ( dbo.aspnet_Users.UserId =
#PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= #PageLowerBound AND
#PageIndexForUsers.IndexId <= #PageUpperBound )
I could use feedback at this point - and, any advice on how to improve
my procedure's logic (if you see anything else that needs improvement) is also appreciated.
Thanks in advance...
ALTER PROCEDURE dbo.wb_Membership_GetAllUsers
#ApplicationName nvarchar(256),
#sortOrderId smallint = 0,
#PageIndex int,
#PageSize int
AS
BEGIN
DECLARE #ApplicationId uniqueidentifier
SELECT #ApplicationId = NULL
SELECT #ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(#ApplicationName) = LoweredApplicationName
IF (#ApplicationId IS NULL)
RETURN 0
-- Set the page bounds
DECLARE #PageLowerBound int
DECLARE #PageUpperBound int
DECLARE #TotalRecords int
SET #PageLowerBound = #PageSize * #PageIndex
SET #PageUpperBound = #PageSize - 1 + #PageLowerBound
BEGIN TRY
-- Create a temp table TO store the select results
CREATE TABLE #PageIndexForUsers
(
IndexId int IDENTITY (0, 1) NOT NULL,
UserId uniqueidentifier
)
-- Insert into our temp table
INSERT INTO #PageIndexForUsers (UserId)
SELECT u.UserId
FROM dbo.aspnet_Membership m, dbo.aspnet_Users u
WHERE u.ApplicationId = #ApplicationId AND u.UserId = m.UserId
ORDER BY u.UserName
SELECT #TotalRecords = ##ROWCOUNT
SELECT dbo.wb_Profiles.profileid, dbo.wb_ProfileData.firstname, dbo.wb_ProfileData.lastname, dbo.wb_Email.emailaddress, dbo.wb_Email.isconfirmed, dbo.wb_Email.emaildomain, dbo.wb_Address.streetname, dbo.wb_Address.cityorprovince, dbo.wb_Address.state, dbo.wb_Address.postalorzip, dbo.wb_Address.country, dbo.wb_ProfileAddress.addresstype,dbo.wb_ProfileData.birthday, dbo.wb_ProfileData.gender, dbo.wb_Session.sessionid, dbo.wb_Session.lastactivitydate, dbo.aspnet_Membership.userid, dbo.aspnet_Membership.password, dbo.aspnet_Membership.passwordquestion, dbo.aspnet_Membership.passwordanswer, dbo.aspnet_Membership.createdate
FROM dbo.wb_Profiles
INNER JOIN dbo.wb_ProfileAddress
ON
(
dbo.wb_Profiles.profileid = dbo.wb_ProfileAddress.profileid
AND dbo.wb_ProfileAddress.addresstype = 'home'
)
INNER JOIN dbo.wb_Address
ON dbo.wb_ProfileAddress.addressid = dbo.wb_Address.addressid
INNER JOIN dbo.wb_ProfileData
ON dbo.wb_Profiles.profileid = dbo.wb_ProfileData.profileid
INNER JOIN dbo.wb_Email
ON
(
dbo.wb_Profiles.profileid = dbo.wb_Email.profileid
AND dbo.wb_Email.isprimary = 1
)
INNER JOIN dbo.wb_Session
ON dbo.wb_Profiles.profileid = dbo.wb_Session.profileid
INNER JOIN
dbo.aspnet_Membership
ON dbo.wb_Profiles.userid = dbo.aspnet_Membership.userid
INNER JOIN
dbo.aspnet_Users
ON dbo.aspnet_Membership.UserId = dbo.aspnet_Users.UserId
INNER JOIN
dbo.aspnet_Applications
ON dbo.aspnet_Users.ApplicationId = dbo.aspnet_Applications.ApplicationId
INNER JOIN
#PageIndexForUsers ON ( dbo.aspnet_Users.UserId =
#PageIndexForUsers.UserId AND #PageIndexForUsers.IndexId >= #PageLowerBound AND
#PageIndexForUsers.IndexId <= #PageUpperBound )
ORDER BY CASE #sortOrderId
WHEN 1 THEN dbo.wb_ProfileData.lastname
WHEN 2 THEN dbo.wb_Profiles.username
WHEN 3 THEN dbo.wb_Address.postalorzip
WHEN 4 THEN dbo.wb_Address.state
END
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK TRAN
EXEC wb_ErrorHandler
RETURN 55555
END CATCH
RETURN #TotalRecords
END
GO
You don't have enough rows in #PageIndexForUsers, no?
If #PageSize = 50 and you want #PageIndex 2, then you are looking for rows 100 to 149 from #PageIndexForUsers. Do you have this many rows?
The row filter should be applied over the larger dataset that starts FROM dbo.wb_Profiles