Counting the total number of characters in a SQL table - sql

I want to count the total number of characters in a table.
I know how to do it for one column:
select sum(leng)
from (
select len(column) as leng
from table
) as Total
But how do I do this for every column in a table?
One way I have thought of is
select sum(len(col1) + len(col2) + len(3) + ...) as TotalChracters
from Table
But I need to do this for over 500 tables, and each table has a lot of columns. I was hoping for a general code that works for one table which I can easily loop over in Python by just changing the table name on each loop.

I have some code that does not run the query but it is almost the same as it will the desired code for any number of tables and columns in your DB.
Also, includes the ISNULL, so, if the table is empty it will show 0:
WITH CTE AS (
SELECT T.Name as Table_Name,
C.Name as Column_Name,
ROW_NUMBER() OVER (PARTITION BY T.Name ORDER BY T.Name, C.Name) AS RowASC,
ROW_NUMBER() OVER (PARTITION BY T.Name ORDER BY T.Name, C.Name DESC) AS RowDESC
FROM sysobjects T
INNER JOIN syscolumns C
ON T.ID = C.ID
WHERE T.XType = 'U'
)
SELECT *,
CASE WHEN RowASC = 1 THEN 'SELECT ISNULL(SUM(' ELSE '' END +
CASE WHEN RowASC = 1 THEN 'LEN('+Column_Name+')' ELSE '+LEN('+Column_Name+')' END +
CASE WHEN RowDESC = 1 THEN '), 0) AS [TotalCharacters on Table: '+Table_Name+']
FROM '+Table_Name +' UNION ' ELSE '' END AS Query
FROM CTE
ORDER BY Table_Name, Column_Name;
Just need to copy the column at the Right (Query) and paste in a new query window.

Related

how to remove other rows with same Word in the SQL table column

how to remove other rows with same Word in the SQL Table column
For example
StudentUserID SessionID
DSteve 101
DSteve 102
CJohn 101
For Reporting purpose we only need first ever row with StudentUserID
You can get the first row that has no overlap with other rows:
select t.*
from t
where not exists (select 1
from t t2
where (t2.name like '%' + t.name + '%' or
t.name like '%' + t2.name + '%'
) and
t2.SessionID < t.SessionID
);
This seems to be technically what you are asking for. It is not clear that this is actually useful.
EDIT:
For your revised question, I'll use a similar query:
select t.*
from t
where not exists (select 1
from t t2
where t2.StudentUserId = t2.StudentuserId and
t2.SessionID < t.SessionID
);
or make it otherwise
WITH b AS (SELECT t.*,
row_number() over(partition by student_name order by student_name ) as _rnk
from t )
SELECT * FROM b WHERE _rnk=1
although the purpose of that reporting is questionable :)
this will give you a unique student name output others will be dropped
but normally you would want to have a unique id for each student because there can be
multiple John Smiths etc.
You can use row_number() :
select t.*
from (select t.*,
row_number() over (partition by StudentUserID order by SessionID) as seq
from table t
) t
where seq = 1;

Find all pairs of identical columns in different tables in a database

I would like to find identical column headers in different tables throughout a database (or across databases). I am trying to learn what are unique or foreign keys in each table fit with other keys in other tables in a multi-database SQL environment (using Teradata), and I think such a query would expedite this process.
I know how to query the database name, table name, and column name, but I don't know how to specify a condition to return only column headers in one table that exist in a different table
Here is some sample code that I think is the starter to this type of query:
select DatabaseName,TABLENAME as Tab1,Columnname as Col1, TABLENAME as Tab2, Columnname as Col2
from DBC.ColumnsV
order by DatabaseName,TABLENAME;
DatabaseName Tab1 Col1 Tab2 Col2
Dat1 Table0 Col0 Table9 Col0
Andrews query simplified:
SELECT DatabaseName, TableName, ColumnName,
Count(*) Over (PARTITION BY ColumnName) AS Cnt
FROM dbc.ColumnsV
QUALIFY Cnt > 1 -- only repeated columns
I think this is enough data to work with, but if you really want pairs of tables you need a self join:
WITH cte AS
(
SELECT DatabaseName, TableName, ColumnName,
Count(*) Over (PARTITION BY ColumnName) AS Cnt
FROM dbc.ColumnsV
WHERE databasename = 'open_data'
QUALIFY Cnt > 1 -- only repeated columns
)
SELECT *
FROM cte AS t1
JOIN cte AS t2
ON t1.ColumnName = t2.ColumnName -- same column
WHERE t1.DatabaseName || '.' || t1.TableName < t2.DatabaseName || '.' || t2.TableName
Of course, this will greatly increase the number of rows, it returns each table name once, thus n*(n-1)/2 rows for n tables with the same column name.
If you change the condition to <> instead of < you get all combinations and twice the number of rows, i,e, both table1,table2 and table2,table1.
First we'll get a list of column names that are duplicated. Then we join that back to ColumnsV and get whatever information you want on those columns.
with cols as (
select
columnname ,
count (*) as cnt
from
dbc.columnsv
group by columnname
having count (*) > 1)
select
columnsv.*
from
dbc.columnsv
inner join cols
on columnsv.columnname = cols.columnname

SQL - multi select query returning no results

I have a query where I'm trying to select a Row Number from a table that meets a certain criteria from a separate table.
The current query returns 0 results when I'm expecting 1 number
SELECT
RowNum
FROM
(SELECT
ID, Name, RowNum = ROW_NUMBER() OVER (ORDER BY ID)
FROM
tblEncroachmentTypes) AS temp
WHERE
temp.Name LIKE (SELECT EN_TYPE
FROM LakeEncroachments
WHERE EN_ID = '0526')
I have created a temp table to try and simplify it, but it still returns no results
select RowNum
from #temp1
where #temp1.Name like (select EN_TYPE from LakeEncroachments where EN_ID = '0526')
I'm trying to give as much information as possible, but not sure what else I need.
If you need to use like, you might need to add the wildcards:
SELECT RowNum
from (Select ID, Name, RowNum = ROW_NUMBER() over (order by ID) from tblEncroachmentTypes) as temp
where temp.Name Like '%'+(Select EN_TYPE from LakeEncroachments WHERE EN_ID = '0526')+'%'
reformat looks like this:
select RowNum
from (
select ID
, name
, RowNum = row_number() over (
order by ID
)
from tblEncroachmentTypes
) as temp
where temp.name like '%' + (
select EN_TYPE
from LakeEncroachments
where EN_ID = '0526'
) + '%'
Also, if your sub query for like returns more than one value, you'll need a different approach.
if your subquery give multiple rows, use this query
WITH temp as
(SELECT ID, Name, ROW_NUMBER() OVER (ORDER BY ID) as RowNum
FROM tblEncroachmentTypes) AS temp
SELECT temp.RowNum
FROM LakeEncroachments
INNER JOIN temp ON temp.Name LIKE REPLACE(REPLACE(LakeEncroachments.EN_TYPE, '-', '% '), ' ', '% ') + '%'
WHERE EN_ID = '0526'

Show Duplicate Items/id in different column

I've made a query to check duplicate items and to display duplicate id's in different columns rather than different rows.
SELECT uid, COUNT(*), Max(id) AS dupes1, MIN(id) AS dupes2
FROM table
GROUP BY uid
HAVING (COUNT(*) > 1)
Another Set of query
SELECT y.uid, x.id
FROM table x
JOIN (SELECT t.uid
FROM table t
GROUP BY t.uid
HAVING COUNT(t.uid) > 1) y ON y.uid = x.uid
where Len(y.uid) > 11
order by y.uid
This works fine for 2 duplicate item's but I want to show all the duplicate items in different columns
Expected Output
uid count dupes1 dupes2 dupes3 and so on...
SELECT uid, COUNT(*),
-- A varchar column to show all duplicates with the format 1,2,3
STUFF((
SELECT ',' + CAST(id AS varchar(10)) FROM table b WHERE a.uid = b.uid FOR XML PATH ('')
), 1, 1, '') AS dupes
FROM table a
GROUP BY uid
HAVING (COUNT(*) > 1)

How to update value if one of the field has multiple same values in SQL

In my database table, one of the fields has the same values. I want to change this value with random number or string which is appended to this field value for uniqueness.
Sample Data
Here 'Ma' has 5 records and so on. I want to change Name Ma01, Ma02 etc.
Id Name Count
1 Ma 5
2 Ga 6
3 Gu 5
How can do with SQL query
Try this
UPDATE TBL
SET Name = A.Name
FROM
(
SELECT
Id,
Name + CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT NULL)) AS NVARCHAR(500)) AS NAME,
Count
FROM
TBL
WHERE
NAME IN
(
SELECT T.NAME FROM TBL T
GROUP BY T.NAME
HAVING COUNT(1) > 1
)
) A
WHERE
TBL.Id = A.ID
Try this:
Select Name + convert(varchar(2), row_number()over(partition by Name order by Name))
From tablename
You just try this.
Declare #i int = 1
update yourtable
set ID = #i , #i = #i + 1
Select Code based on NEER`s code with leading zero added, tested on MSSQL database.
SELECT
Id,
Name,
Name + RIGHT('00'+CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT Name)) AS NVARCHAR(MAX)),2) AS Updatedname
FROM
tablename
WHERE
Name IN
(
SELECT T.NameFROM tablename T
GROUP BY T.Name
HAVING COUNT(Name) > 1
)
GROUP BY Name,Id
ORDER BY Name