SQL query - 'ON' clause - sql-server-2008-r2

I have the below query and I need to add another condition on 'ON' clause.
If I need to include another clause for 'ON' which is
i_no = LEFT(replace(right(filename, charindex('\', reverse(filename))-1),'_rprt%[0-9]%.doc', ''),
How do I achieve this?
SELECT (right(filename, charindex('\', reverse(filename))-1)) phyname,
replace(filename,(right(filename, charindex('\', reverse(filename))-1)), '') phypath,
a_no,
i_no
from
#tempimages
inner join
imagestatus
on
i_no = LEFT(replace(right(filename, charindex('\', reverse(filename))-1),'.doc', ''),
LEN(replace(right(filename, charindex('\', reverse(filename))-1),'.doc', ''))-3)

If you want to only return records where both of the conditions in your ON clause are true, then use AND:
SELECT (RIGHT(filename, CHARINDEX('\', REVERSE(filename))-1)) phyname,
REPLACE(filename,(RIGHT(filename, CHARINDEX('\', REVERSE(filename))-1)), '') phypath,
a_no,
i_no
FROM #tempimages
INNER JOIN imagestatus ON i_no = LEFT(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'.doc', ''),LEN(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'.doc', ''))-3)
AND i_no = LEFT(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'_rprt%[0-9]%.doc', '')
If records should be returned if either of the conditions are met, then use OR:
SELECT (RIGHT(filename, CHARINDEX('\', REVERSE(filename))-1)) phyname,
REPLACE(filename,(RIGHT(filename, CHARINDEX('\', REVERSE(filename))-1)), '') phypath,
a_no,
i_no
FROM #tempimages
INNER JOIN imagestatus ON i_no = LEFT(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'.doc', ''),LEN(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'.doc', ''))-3)
OR i_no = LEFT(REPLACE(right(filename, CHARINDEX('\', REVERSE(filename))-1),'_rprt%[0-9]%.doc', '')

Related

How to list all constraints of a table in PostgreSQL?

How to list all constraints (Primary key, Foreign Key, check, unique mutual exclusive, ..) of a table in PostgreSQL?
Constraints of the table can be retrieved from catalog-pg-constraint. using the SELECT query.
SELECT con.*
FROM pg_catalog.pg_constraint con
INNER JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid
INNER JOIN pg_catalog.pg_namespace nsp ON nsp.oid = connamespace
WHERE nsp.nspname = '{schema name}'
AND rel.relname = '{table name}';
and the same can be viewed in PSQL using
\d+ {SCHEMA_NAME.TABLE_NAME}
Here is POSTGRES specific answer
..... it will retrive all columns and their relationship as well
SELECT * FROM (
SELECT
pgc.contype as constraint_type,
pgc.conname as constraint_name,
ccu.table_schema AS table_schema,
kcu.table_name as table_name,
CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE ccu.COLUMN_NAME END as column_name,
CASE WHEN (pgc.contype = 'f') THEN ccu.TABLE_NAME ELSE (null) END as reference_table,
CASE WHEN (pgc.contype = 'f') THEN ccu.COLUMN_NAME ELSE (null) END as reference_col,
CASE WHEN (pgc.contype = 'p') THEN 'yes' ELSE 'no' END as auto_inc,
CASE WHEN (pgc.contype = 'p') THEN 'NO' ELSE 'YES' END as is_nullable,
'integer' as data_type,
'0' as numeric_scale,
'32' as numeric_precision
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
UNION
SELECT null as constraint_type , null as constraint_name , 'public' as "table_schema" ,
table_name , column_name, null as refrence_table , null as refrence_col , 'no' as auto_inc ,
is_nullable , data_type, numeric_scale , numeric_precision
FROM information_schema.columns cols
Where 1=1
AND table_schema = 'public'
and column_name not in(
SELECT CASE WHEN (pgc.contype = 'f') THEN kcu.COLUMN_NAME ELSE kcu.COLUMN_NAME END
FROM
pg_constraint AS pgc
JOIN pg_namespace nsp ON nsp.oid = pgc.connamespace
JOIN pg_class cls ON pgc.conrelid = cls.oid
JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = pgc.conname
LEFT JOIN information_schema.constraint_column_usage ccu ON pgc.conname = ccu.CONSTRAINT_NAME
AND nsp.nspname = ccu.CONSTRAINT_SCHEMA
)
) as foo
ORDER BY table_name desc
I wasn't able to get the above solutions to work. Maybe they're no longer supported or more likely I'm doing something wrong. This is how I got it to work. Note that the "contype" column will be abbreviated with the constraint type (e.g. 'c' for check, 'p' for primary key, etc.). I include that variable in case you want to add a WHERE statement to filter for it after the FROM block.
select pgc.conname as constraint_name,
ccu.table_schema as table_schema,
ccu.table_name,
ccu.column_name,
contype,
pg_get_constraintdef(pgc.oid)
from pg_constraint pgc
join pg_namespace nsp on nsp.oid = pgc.connamespace
join pg_class cls on pgc.conrelid = cls.oid
left join information_schema.constraint_column_usage ccu
on pgc.conname = ccu.constraint_name
and nsp.nspname = ccu.constraint_schema
order by pgc.conname;
SELECT constraint_name, table_name, column_name, ordinal_position FROM information_schema.key_column_usage WHERE table_name = 'put your table name here';

SELECT with CASE WHEN and value after THEN instead of String

My query is:
SELECT
id,
CASE WHEN EXISTS(
SELECT
data_od
FROM
bp_stan_produkt
WHERE
id_produkt = bp_produkt.id AND data_do IS NULL AND id_stan_produkt = 313
) THEN 'TAK' ELSE 'NIE'
END AS "313"
FROM
bp_produkt
WHERE
id IN(21048528)
Is it possible to put data_od to column 313 instead of TAK or do I have to create function, make SELECT data_od into some_variable and then some_variable?
Yes it is possible:
select id,
case when exists (select data_od from bp_stan_produkt
where id_produkt = bp_produkt.id and data_do is null
and id_stan_produkt = 313)
then (select to_char(data_od, 'YYYY-MM-DD')
from bp_stan_produkt
where id_produkt = bp.id
and data_do is null
and id_stan_produkt = 313)
else 'NIE'
end as "313"
from bp_produkt
where id in(21048528);
EDIT:
SELECT bp.id, COALESCE(t.data_od_t, 'NIE') AS "313"
FROM bp_produkt bp
LEFT JOIN LATERAL (select to_char(data_od, 'YYYY-MM-DD') AS data_od_t
from bp_stan_produkt
where id_produkt = bp.id
and data_do is null
and id_stan_produkt = 313) t
ON TRUE
WHERE bp.id in(21048528)

How to write valid If clause inside select or write function

I have procedure like this and I get error in If clause. I think it is because COUNT. But my clause have to be like that so I don't know how to solve it. Maybe it would be good to create a function or something similar. Rest of the code is okay
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
)
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
if( (SELECT COUNT(UstrojstvenaJedinicaId) FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS') = 1)
begin
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
end
ELSE
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
end
ERROR is here in Group by and I don't know why.
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
SELECT
tu.Id,
tu.UstrojstvenaJedinica AS 'UstrojstvenaJedinica',
tu.VrstaUgovora AS 'VrstaUgovora',
tu.KlasaUgovora AS 'KlasaUgovora',
tu.UrudzbeniBrojUgovora AS 'UrudzbeniBrojUgovora',
tu.DatumIstekaUgovora AS 'DatumPocetkaUgovora',
tu.DatumIstekaUgovora AS 'DatumIstekaUgovora',
ISNULL(STRING_AGG(LTRIM(RTRIM(p.Naziv)), ', '), '') as 'Partner'
FROM #TempUgovori AS tu
LEFT JOIN VezaUgovorPartner AS vup
on tu.Id = vup.UgovorId
LEFT JOIN [TEST_MaticniPodaci2].dbo.Partner as p
ON vup.PartnerId = p.PartnerID
GROUP BY tu.Id, tu.UstrojstvenaJedinica, tu.VrstaUgovora, tu.KlasaUgovora, tu.UrudzbeniBrojUgovora, tu.DatumPocetkaUgovora, tu.DatumIstekaUgovora
END
EXEC [TEST_Ugovori_Prod].[dbo].[DohvatiSve] 6;
GO
I am sorry for too much code but without it I can't run query.
It looks like you're trying to tell SQL Server to join to VezaUgovorUstrojstvenaJedinica differently depending on the circumstances. The sql engine can't figure that out. For a very brief discussion on how sql evaluates a query, here's a start:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries?forum=transactsql
Maybe something like this will work for you?
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
);
DECLARE #HCPHS integer;
SELECT
#HCPHS = COUNT(UstrojstvenaJedinicaId)
FROM
VezaUgovorUstrojstvenaJedinica
WHERE
UstrojstvenaJedinicaId = 'HCPHS';
IF #HCPHS = 1
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
ELSE
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora

List all index names, column names and its table name of a PostgreSQL database

What is the query to get the list all index names, its column name and its table name of a postgresql database?
I have tried to get the list of all indexes in a db by using this query but how to get the list of indexes, its column names and its table names?
SELECT *
FROM pg_class, pg_index
WHERE pg_class.oid = pg_index.indexrelid
AND pg_class.oid IN (
SELECT indexrelid
FROM pg_index, pg_class
WHERE pg_class.oid=pg_index.indrelid
AND indisunique != 't'
AND indisprimary != 't'
AND relname !~ '^pg_');
This will output all indexes with details (extracted from my view definitions):
SELECT i.relname as indname,
i.relowner as indowner,
idx.indrelid::regclass,
am.amname as indam,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
FROM generate_subscripts(idx.indkey, 1) as k
ORDER BY k
) as indkey_names,
idx.indexprs IS NOT NULL as indexprs,
idx.indpred IS NOT NULL as indpred
FROM pg_index as idx
JOIN pg_class as i
ON i.oid = idx.indexrelid
JOIN pg_am as am
ON i.relam = am.oid;
Optionally add an extra join to the end so as to trim the namespaces:
SELECT i.relname as indname,
i.relowner as indowner,
idx.indrelid::regclass,
am.amname as indam,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, true)
FROM generate_subscripts(idx.indkey, 1) as k
ORDER BY k
) as indkey_names,
idx.indexprs IS NOT NULL as indexprs,
idx.indpred IS NOT NULL as indpred
FROM pg_index as idx
JOIN pg_class as i
ON i.oid = idx.indexrelid
JOIN pg_am as am
ON i.relam = am.oid
JOIN pg_namespace as ns
ON ns.oid = i.relnamespace
AND ns.nspname = ANY(current_schemas(false));
More human friendly version of #Denis solution:
SELECT
U.usename AS user_name,
ns.nspname AS schema_name,
idx.indrelid :: REGCLASS AS table_name,
i.relname AS index_name,
idx.indisunique AS is_unique,
idx.indisprimary AS is_primary,
am.amname AS index_type,
idx.indkey,
ARRAY(
SELECT pg_get_indexdef(idx.indexrelid, k + 1, TRUE)
FROM
generate_subscripts(idx.indkey, 1) AS k
ORDER BY k
) AS index_keys,
(idx.indexprs IS NOT NULL) OR (idx.indkey::int[] #> array[0]) AS is_functional,
idx.indpred IS NOT NULL AS is_partial
FROM pg_index AS idx
JOIN pg_class AS i
ON i.oid = idx.indexrelid
JOIN pg_am AS am
ON i.relam = am.oid
JOIN pg_namespace AS NS ON i.relnamespace = NS.OID
JOIN pg_user AS U ON i.relowner = U.usesysid
WHERE NOT nspname LIKE 'pg%'; -- Excluding system tables
The Query to list all the indexes of a database
SELECT
tablename,
indexes [1],
indexes [2],
indexes [3],
indexes [4],
indexes [5],
indexes [6],
indexes [7],
indexes [8],
indexes [9],
indexes [10]
FROM (SELECT
tablename,
array_agg(indexname) AS indexes
FROM pg_indexes
WHERE schemaname = 'public'
GROUP BY tablename) as sub;
Here's a version that simplifies things compared to other answers by
avoiding nested selects
avoiding built-in functions (maybe hard to remember)
using LATERAL and UNNEST(...) WITH ORDINALITY features available in later PostgreSQL versions (9.4+)
SELECT
tnsp.nspname AS schema_name,
trel.relname AS table_name,
irel.relname AS index_name,
array_agg (
a.attname
|| ' ' || CASE o.option & 1 WHEN 1 THEN 'DESC' ELSE 'ASC' END
|| ' ' || CASE o.option & 2 WHEN 2 THEN 'NULLS FIRST' ELSE 'NULLS LAST' END
ORDER BY c.ordinality
) AS columns
FROM pg_index AS i
JOIN pg_class AS trel ON trel.oid = i.indrelid
JOIN pg_namespace AS tnsp ON trel.relnamespace = tnsp.oid
JOIN pg_class AS irel ON irel.oid = i.indexrelid
CROSS JOIN LATERAL unnest (i.indkey) WITH ORDINALITY AS c (colnum, ordinality)
LEFT JOIN LATERAL unnest (i.indoption) WITH ORDINALITY AS o (option, ordinality)
ON c.ordinality = o.ordinality
JOIN pg_attribute AS a ON trel.oid = a.attrelid AND a.attnum = c.colnum
GROUP BY tnsp.nspname, trel.relname, irel.relname
If you are also interested in index size, you may use this query from the PostgreSQL Wiki.
SELECT
t.tablename,
indexname,
c.reltuples AS num_rows,
pg_size_pretty(pg_relation_size(quote_ident(t.tablename)::text)) AS table_size,
pg_size_pretty(pg_relation_size(quote_ident(indexrelname)::text)) AS index_size,
CASE WHEN indisunique THEN 'Y'
ELSE 'N'
END AS UNIQUE,
idx_scan AS number_of_scans,
idx_tup_read AS tuples_read,
idx_tup_fetch AS tuples_fetched
FROM pg_tables t
LEFT OUTER JOIN pg_class c ON t.tablename=c.relname
LEFT OUTER JOIN
( SELECT c.relname AS ctablename, ipg.relname AS indexname, x.indnatts AS number_of_columns, idx_scan, idx_tup_read, idx_tup_fetch, indexrelname, indisunique FROM pg_index x
JOIN pg_class c ON c.oid = x.indrelid
JOIN pg_class ipg ON ipg.oid = x.indexrelid
JOIN pg_stat_all_indexes psai ON x.indexrelid = psai.indexrelid )
AS foo
ON t.tablename = foo.ctablename
WHERE t.schemaname='public'
ORDER BY 1,2;
For Non-Composite Indexes
select t.relname,i.relname ,
STRING_AGG(pga.attname||'', ','order by i.relname,pga.attnum) as columnName
from pg_class t inner join pg_index ix
on t.oid = ix.indrelid
inner join pg_class i
on i.oid = ix.indexrelid
inner join pg_attribute pga
on
pga.attrelid = i.oid
inner join pg_indexes pgidx
on pgidx.indexname=i.relname
where
t.relkind = 'r'
and pgidx.schemaname='asit_cm'
and t.relname ='accessory'
group by t.relname,i.relname having count(*)=1
For Composite Indexes
select t.relname,i.relname ,
STRING_AGG(pga.attname||'', ','order by i.relname,pga.attnum) as columnName
from pg_class t inner join pg_index ix
on t.oid = ix.indrelid
inner join pg_class i
on i.oid = ix.indexrelid
inner join pg_attribute pga
on
pga.attrelid = i.oid
inner join pg_indexes pgidx
on pgidx.indexname=i.relname
where
t.relkind = 'r'
and pgidx.schemaname='asit_cm'
and t.relname ='accessory'
group by t.relname,i.relname having count(*)=1

SQL to split string and put to lower case?

I have a User_Id column with data DOMAIN\USERID
I need it to be DOMAIN\userid
Whats the (sql server) sql?
Update:
Answer from #David McEwing
update UserTable
set [User_Id] = SUBSTRING( [User_Id], 0, CHARINDEX('\', [User_Id])+1)
+ lower(SUBSTRING( [User_Id], CHARINDEX('\', [User_Id])+1, len( [User_Id])))
SELECT LEFT(User_Id, CHARINDEX('\', User_Id)) -- grabs DOMAIN and '\'
+ LOWER(RIGHT(User_Id,
LEN(User_Id) - CHARINDEX('\', User_Id))) -- concat with lower of userid
FROM MyTable
This should do the trick:
declare #name varchar(50)
set #name= 'DOMAIN\USERID'
select SUBSTRING(#name, 0, CHARINDEX('\', #name)+1)
+ lower(SUBSTRING(#name, CHARINDEX('\', #name)+1, len(#name)))