Want title on TOP from Oracle query - asp.net

With the below query I generate a datable whose diagram is as below:-
SELECT *
FROM (SELECT DISTINCT sv.mkey, vehicle_no,
CASE
WHEN sv.audit_flag = 'N'
THEN 'REJECTED'
ELSE 'PENDING APPROVAL'
END isnullcheck,
TO_CHAR (date_in,
'dd-MM-yyyy'
)
|| ' & '
|| time_in vehicleindate_time,
TO_CHAR (date_out,
'dd-MM-yyyy'
)
|| ' & '
|| time_out vehicleoutdate_time,
gate_no_in || ' & ' || gate_no_out ingate_outgateno,
remark_in remarkin, NULL receipt_no, date_in,
CASE
WHEN sv.audit_flag = 'N'
THEN 'Y'
ELSE 'N'
END hod
FROM xxcus.xxgid_audit_entry sv
WHERE sv.project_id = '1365'
AND (sv.audit_flag IS NULL OR sv.audit_flag = 'N')
UNION
SELECT NULL, NULL, 'PENDING APPROVAL', NULL, 'PENDING APPROVAL',
NULL, NULL, NULL, NULL, NULL
FROM DUAL
UNION
SELECT NULL, NULL, 'REJECTED', NULL, 'REJECTED', NULL, NULL, NULL,
NULL, NULL
FROM DUAL) qq
ORDER BY isnullcheck DESC
the generated datable is as below
[![Datatable][1]][1]
Now what, I want is.
The query will fetch result into two headings
ie. 1. REJECTED or 2. PENDING APPROVAL
but what happening here is it is going other than both the heading also. It should not go.
[![Image][2]][2]
Also see the html of grid
How to make that under two headings ?? is there any issue with query ?

Order by something else as well, and used NULLS FIRST on that:
ORDER BY isnullcheck DESC, mkey NULLS FIRST

Related

Issues with postgresql-11 partitioning and primary key autoincrement

Primary key on partitioned tables is incremented by n(n>1) and not by 1.
Tried to rewrite plpgsql in numerous different ways with no luck.
There must be something I am not understanding.
CREATE SCHEMA IF NOT EXISTS some_record_pool;
CREATE SEQUENCE some_record_pkey_seq;
create table some_record
(
id BIGINT not null DEFAULT nextval('some_record_pkey_seq'::regclass),
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
CREATE INDEX idx_device_id
ON public.some_record USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.some_record USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.some_record (cast(created_time as DATE));
----- CREATE TRIGGER ----------
CREATE OR REPLACE FUNCTION some_record_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition_name := 'some_record_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS
(SELECT 1
FROM information_schema.tables
WHERE table_name = partition_name)
THEN
RAISE NOTICE 'A partition has been created %', partition_name;
EXECUTE format(
E'CREATE TABLE some_record_pool.%I ' ||
E'(CHECK ( date_trunc(\'day\', created_time) >= ''%s'' ' ||
E'AND date_trunc(\'day\', created_time) < ''%s'')) INHERITS (public.some_record)',
partition_name, start_of_month, end_of_next_month);
-- EXECUTE format('GRANT SELECT ON TABLE %I TO readonly',
-- partition_name); -- use this if you use role based permission
ELSE
RAISE NOTICE 'A partition DOES NOT EXIST %', partition_name;
END IF;
EXECUTE format(
'INSERT INTO some_record_pool.%I (device_id, device_type, ' ||
'record_time, module_serial_number, module_id, message_type, ' ||
'event_code, device_status, sequence_number, data_bytes, device_data,' ||
' active, deleted) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)',
partition_name) using NEW.device_id, NEW.device_type,
NEW.record_time, NEW.module_serial_number, NEW.module_id, NEW.message_type,
NEW.event_code, NEW.device_status, NEW.sequence_number, NEW.data_bytes,
NEW.device_data, NEW.active, NEW.deleted;
RETURN NEW;
END
$$
LANGUAGE plpgsql;
CREATE TRIGGER insert_some_record_trigger
BEFORE INSERT ON public.some_record
FOR EACH ROW EXECUTE PROCEDURE public.some_record_insert_function();
--- INSERTING DATA FOR TESTING
INSERT INTO some_record (
event_record_id, timestamp, event_description_id, event_source_label, event_source_track, event_source_direction,
measurement_description, measurement_value, hw_address_module_id, hw_address_rlc_address, sub_system_source,
event_type, device_id, active, deleted) VALUES(1, 2, to_timestamp('1953-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), 1, 1, 1, 1, NULL, 1, 9, E'9 B
00000000 92 FF 3C 00 7F 00 00 03 E8 .ÿ<.....è
', TRUE, FALSE, to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'));
The point of the code is to auto create partitions and insert data if partition exists.
Primary key should be incremented by one but it is not behaving as such
expected output on only one run is id: 1
Working solution tested on postgres 12 is the following:
/** TABLE PARTITIONING EVENT RECORD **/
-- CREATE PROPER SCHEMA
CREATE SCHEMA IF NOT EXISTS test_par_pool;
-- CREATE PROPER TABLE
CREATE TABLE test_part
(
id bigserial not null
constraint test_part_pkey
primary key,
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
-- CREATE MINIMAL INDEXES
CREATE INDEX idx_device_id
ON public.test_part USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.test_part USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.test_part (cast(created_time as DATE));
-- CREATE INSERT FUNCTIONS
CREATE OR REPLACE FUNCTION test_par_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
stmt TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition := TG_RELNAME || '_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname = partition) THEN
RAISE NOTICE 'A partition has been created %',partition;
stmt = 'CREATE TABLE test_par_pool.' || partition || ' (check (date_trunc(''day'', created_time) >= '
|| chr(39) || start_of_month || chr(39)
|| ' AND date_trunc(''day'', created_time) < '
|| chr(39) || end_of_next_month
|| chr(39) || ' )) INHERITS ( public.' || TG_RELNAME ||
');';
EXECUTE stmt;
END IF;
EXECUTE 'INSERT INTO test_par_pool.' || partition ||
' SELECT( public.' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING id;';
RETURN NULL;
END
$$
LANGUAGE plpgsql;
-- CREATE TRIGGER
CREATE TRIGGER insert_test_part_trigger
BEFORE INSERT ON public.test_part
FOR EACH ROW EXECUTE PROCEDURE public.test_par_insert_function();

MS SQL Case in Where Clause testing against NULL or Argument

I have a query against a UDF where I want to allow the user to pass in either ALL or a specific EType.
If they pass in ALL, I want to accept all ETypes where it is not null.
I have searched thru SO for examples and not seem to meet my particular situation.
Where am I going wrong?
Declare
#company varchar(4),
#charge_cov bit,
#EType varchar(8);
set #company = '123'
set #charge_cov =1
set #EType = 'ALL'
select e.emp_id,
dbo.format_emp_number(pd.EN) as EN,
dbo.format_emp_number(pd.MEN) as MEN,
pd.EType
from dbo.employee_payroll_data(NULL) pd
inner join employee e on (e.emp_id=pd.emp_id)
where pd.EType = case when #EType='ALL' then pd.EType
else #EType ) END
and pd.EType is not null
and e.emp_number is not null
and e.charge_cov = 1
and lc.pr_co_code = #company
Try below code:
WHERE (((1 = (CASE WHEN #EType = 'ALL' THEN 1 ELSE 0 END)))
OR ((pd.Etype = (CASE WHEN #EType <> 'ALL' THEN #EType ELSE '' END))))
AND pd.Etype IS NOT NULL

Data is not getting fetched when status is Pending in PLSQL

I want to download an excel report based on State and Status. And for getting that data I am calling an SP whose query is below
SELECT * FROM UBR_STRUCTURE_DETAILS WHERE (STATE = P_STATE) AND (NE_STATUS = P_STATUS);
there are lot's of data for the query but I am not getting a single record.
State -> Maharashtra
Status -> Pending.
NOTE IF status is pending the value in UBR_STRUCTURE_DETAILS for status column is ''
update
PROCEDURE GET_DATA_WITH_STATUS_EXL
(
P_STATE NVARCHAR2,
P_STATUS VARCHAR2,
TBL_STATE_REP OUT SYS_REFCURSOR
)
AS
BEGIN
OPEN TBL_STATE_REP FOR
SELECT * FROM UBR_STRUCTURE_DETAILS WHERE (STATE = P_STATE) AND (NE_STATUS = P_STATUS);
NULL;
END GET_DATA_WITH_STATUS_EXL;
Can you try this:
PROCEDURE GET_DATA_WITH_STATUS_EXL
(
P_STATE NVARCHAR2,
P_STATUS VARCHAR2,
TBL_STATE_REP OUT SYS_REFCURSOR
)
AS
BEGIN
OPEN TBL_STATE_REP FOR
SELECT * FROM UBR_STRUCTURE_DETAILS
WHERE (STATE = P_STATE) AND (NE_STATUS = P_STATUS OR P_STATUS = 'Pending' AND NE_STATUS IS NULL);
NULL;
END GET_DATA_WITH_STATUS_EXL;
Simulation for xing, who had some doubts:
CREATE TABLE T_R (ID NUMBER(5,0), NE_STATUS VARCHAR(20));
INSERT INTO T_R VALUES (1,'Pending');
INSERT INTO T_R VALUES (2,'Not Pending');
INSERT INTO T_R VALUES (3,NULL);
INSERT INTO T_R VALUES (4,'');
Extract Pending
SELECT * FROM T_R
WHERE NE_STATUS = 'Pending' OR 'Pending' = 'Pending' AND NE_STATUS IS NULL;
Output:
1 Pending
3 (null)
4 (null)
Extract Others
SELECT * FROM T_R
WHERE NE_STATUS = 'Not Pending' OR 'Not_Pending' = 'Pending' AND NE_STATUS IS NULL;
Output:
2 Not Pending
The one possibilty i can see if CASE and SPACE when you put the joining condition. I would say to convert the input string and table column to same case and trim the spaces while doing a match. See below:
NOTE IF status is pending the value in UBR_STRUCTURE_DETAILS for
status column is ''
PROCEDURE GET_DATA_WITH_STATUS_EXL (P_STATE NVARCHAR2,
P_STATUS VARCHAR2,
TBL_STATE_REP OUT SYS_REFCURSOR)
AS
BEGIN
OPEN TBL_STATE_REP FOR
SELECT *
FROM UBR_STRUCTURE_DETAILS
WHERE DECODE (NE_STATUS, NULL, 'Y', TRIM (LOWER (NE_STATUS))) = CASE
WHEN INITCAP (P_STATUS) = 'Pending' THEN 'Y'
ELSE TRIM (LOWER (P_STATUS))
END
AND TRIM (LOWER (STATE)) = TRIM (LOWER (P_STATE));
-- NULL;
END GET_DATA_WITH_STATUS_EXL;
In SP your query look like this
SELECT * FROM UBR_STRUCTURE_DETAILS WHERE (STATE = #P_STATE) AND (NE_STATUS = #P_STATUS)
You have to pass a value to parameter in sqlcomman object.
For example:
sqlcomman.parameter.add("#P_STATE",stringState);

How can I write two update queries in single stored procedure in SQL Server 2008

I have a table that contains a few columns bound to a gridview.
In that gridview, I have an edit option to update the columns. In that situation I need to write a two update stored procedures that means I select all columns expect AudiotoName, select another columns all columns are update to raise one update query but when I select table in that have AudiotoName column that only edit to select that column it will raise second update stored procedure. I tried but it not properly working can anyone help me out.
My code:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END
Can anyone help me out?
The problem in your query is that, even if #AuditoName is true, the lower update query is running. This will re-update the table SubjectItems. You can use if...else block instead, like below:
ALTER PROCEDURE up_file
(#ModuleID int,
#SubjectID int,
#Physician varchar(500) = '',
#AuditoName varchar(300) = '',
#AuditoType varchar(50) = '',
#AudioPath varchar(2000) = '',
#BaseDocumentName varchar(500) = '',
#BaseDocumentPath varchar(2000) = '',
#Createddate datetime,
#CreatedBy varchar(200) = '')
AS
BEGIN
IF #AuditoName = 'true' //select AuditoName column only raise this update query
BEGIN
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE AuditoName = #AuditoName
END
ELSE
BEGIN //normal fields select raise this update query
UPDATE SubjectItems
SET ModuleID = #ModuleID,
SubjectID = #SubjectID,
Physician = '#Physician',
AuditoName = '#AuditoName',
AuditoType = '#AuditoType',
AudioPath ='#AudioPath',
BaseDocumentName = '#BaseDocumentName',
BaseDocumentPath = '#BaseDocumentPath'
WHERE ModuleID = #ModuleID
END
END

Search specific value in all field in oracle table

I want to search some keyword in table but I don't know to which column it is belonging to. I have got one of query for that as follows:
variable val varchar2(10)
exec :val := 'KING'
PL/SQL procedure successfully completed.
SELECT DISTINCT SUBSTR (:val, 1, 11) "Searchword",
SUBSTR (table_name, 1, 14) "Table",
SUBSTR (column_name, 1, 14) "Column" FROM cols,
TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '
|| column_name
|| ' from '
|| table_name
|| ' where upper('
|| column_name
|| ') like upper(''%'
|| :val
|| '%'')' ).extract ('ROWSET/ROW/*') ) ) t
ORDER BY "Table"
Searchword Table Column
KING EMP ENAME
but I am not getting appropriate output.I only got output as:
PL/SQL procedure successfully completed. I have tried but I didn't get satisfactory answer. Can anybody please help..?
The easiest query I can write for such scope is something like:
SELECT *
FROM <table>
WHERE UPPER(column1) LIKE UPPER('%' || :val || '%')
OR UPPER(column2) LIKE UPPER('%' || :val || '%')
OR UPPER(column3) LIKE UPPER('%' || :val || '%')
OR UPPER(column4) LIKE UPPER('%' || :val || '%');
In this query I search for value :val in all columns of the table using OR conditions, so if at least one column contains the value the row is fetched
If you have many columns you can write a query that builds the final query for you, like the following:
SELECT 'SELECT * FROM <table> WHERE ' || LISTAGG(column_name || ' LIKE ''%' || :val || '%''', ' OR ') WITHIN GROUP (ORDER BY column_name)
FROM dba_tab_columns
WHERE table_name = '<table>'
The result of this query is the query to execute. Note that Oracle has a limit of 4000 characters for a string field built in a query. If your where condition is too big the query will fail.
In this case, the only alternative is to write a stored procedure that builds the query and returns it in a CLOB variable, here's an example:
CREATE OR REPLACE FUNCTION build_query(in_table_name IN VARCHAR2, in_search IN VARCHAR2) RETURN `CLOB` IS
lc_query CLOB := 'SELECT * FROM ' || in_table_name || ' WHERE 1=0';
BEGIN
FOR c IN (
SELECT *
FROM user_tab_columns
WHERE table_name = in_table_name
ORDER BY column_name
) LOOP
lc_query := lc_query || ' OR ' || c.column_name || ' LIKE ''%' || in_search || '%''';
END LOOP;
RETURN lc_query;
END;
This function will works and generates strings longer than 4000 characters.

Resources