Total length off all characters in all columns of each row - sql-server

I'm new to SQL Server so I apologize if my question seems too easy. I tried finding and answer on my own, but I'm failing miserably. I am trying to create a query which will return total size on the drive of each row in the table.
i thought about using dbcc showconting but it doesn't work for varchar(max) which appears in my table. Also, it doesn't return size for each row, but rather the average, max and min size. My reading so far suggests that it is not possible to get query that could show the size of each individual row in the table so I decided to settle for the total length of all characters in each column in each row. Indirectly it will give me idea about the size of each row.
I have a table with some varchar(500) and varchar(max) columns. I noticed that some of the rows are a lot bigger than others.
What I need is top 1000 longest rows in the table, preferably in an output showing two columns:
Column 1 showing EntryID
Column 2 showing total length of the characters in all columns together for that record (eg total length of the characters in the column 1 + total length of the characters in the column 2 + column3 + column4 etc...) It would be great if this could be aliased RowLength.
What I tried so far is:
SELECT TOP 1000
(LEN(columnname1) + LEN(columnname2) + LEN(columnname3) + LEN(columnname4)) as RowLength,
FROM dbo.tablename
ORDER BY Length Desc
It works, but it doesn't show entry ID corresponding to the total length of all characters in the row. How do I add it?
It also doesn't show the alias for the column showing number of characters in the row.
Could you please suggest how I can change the query to get the expected outcome? I'll be very grateful for any suggestions.

it doesn't show EntryID corresponding to the total length of all
characters in the row. It also doesn't show the alias for the column
showing number of characters in the row.
You have not specified an alias, so what should it show? You also haven't selected EntryID. If you want the longest 1000 rows you have to order by the length:
SELECT TOP 1000
EntryID,
Length = LEN(columnname1) + LEN(columnname2) + LEN(columnname3) + LEN(columnname4)
FROM dbo.tablename
ORDER BY Length DESC

SELECT TOP 1000 EntryID,
(LEN(columnname1) + LEN(columnname2) + LEN(columnname3) + LEN(columnname4)) AS RowLength,
FROM dbo.tablename
ORDER BY EntryID

Related

ISBLANK(...) = FALSE even thought the cell is blank in google sheet

Hi everyone,
I have 2 tables, 3rd column for Table 1 is Value 1 and 3rd column for Table 2 is Value 2. I combined these 2 tables by expanding both tables first so that all the columns are aligned as shown in the screenshot above (Column E to Column H).
The formula in all the yellow cells are:
Cell E4 : =QUERY(A4:C10,"Select A,B,C,' ' label ' ' 'Value 2' ")
Cell E12 : =QUERY(A12:C20,"Select A,B,' ',C label ' ' 'Value 1' ")
Cell K7 : =QUERY({E5:H10;E13:H17},"Select * where Col1 is not null",0)
Cell P7 : =ArrayFormula(IF(ISBLANK(M7:M12),100,M7:M12))
In column P, I want to return 100 as Value 1 if the cells in Column M is blank. So by right I should get 2,34,55,100,100,100 in column P but right now the formula still return 3 blank cells.
I suspect that is because the QUERY function that I used before which make the cell is not blank although it seems like still a blank cell. May I know is there any trick that I can use to find the blank cells in column M and column N (preferably don't touch the QUERY formula) since ISBLANK() is not working in this case?
Any help or advise will be greatly appreciated!
Edited
makes sense. you cant use ISBLANK because cell is not blank. remember that QUERY inserted an empty space.
try:
=ARRAYFORMULA(IF(ISBLANK(TRIM(M7:M12)), 100, M7:M12))
ISBLANK is so sensitive that it will detect even residue from TRIM
update:
=ARRAYFORMULA(IF(TRIM(M7:M12)="", 100, M7:M12))

Max If array formula with multiple criteria (no pivot tables)

I'm trying to return the MAX date [G-Step Complete]
for a series of rows with same values [CONCAT],
IF the date column [G-Step Complete] does NOT contain a BLANK. However, if the date column [G-Step Complete] does contain a BLANK, return 0.
This is the array formula I am working with:
=MAX(IF([CONCAT]=[#CONCAT],IF(ISBLANK([G-Step Complete]),0,[G-Step Complete])))
The [CONCAT] column is sorted such that like items are grouped together.
My expectation is that IF any rows for a given group of CONCAT values is blank, then I would expect a result of 0. If NO rows contain a BLANK, then I would expect the value to return the MAX date.
With TB being the name of the table, this should do in Excel 2007 (and above) syntax:
=IF(SUMPRODUCT(([CONCAT]=TB[[#This Row],[CONCAT]])*ISBLANK([G-Step Complete])),0,
LARGE([G-Step Complete]*(([CONCAT] = TB[[#This Row],[CONCAT]])), 1))
could be shortened with the # operator in Excel 2010 and above versions:
=IF(SUMPRODUCT(([CONCAT]=[#CONCAT])*ISBLANK([G-Step Complete])),0,
LARGE([G-Step Complete]*(([CONCAT]=[#CONCAT])), 1))

Adding Numbers to get the target Numbers

I want to generate a random number against StudentID, I am using the following SQL
The Result i am getting is :
Please Help.
You're just setting that column to the column index of the partitioned row_number, which is 1. If you want a random number for each row, it would be easier to do this:
UPDATE TAB_EXAM_FORMS
SET RNO_CODE = CAST(RAND(CHECKSUM(NEWID())) * 10 AS INT) + 1
Just change the multiplication to whatever range you want. This range is 1-10.

Right pad a string with variable number of spaces

I have a customer table that I want to use to populate a parameter box in SSRS 2008. The cust_num is the value and the concatenation of the cust_name and cust_addr will be the label. The required fields from the table are:
cust_num int PK
cust_name char(50) not null
cust_addr char(50)
The SQL is:
select cust_num, cust_name + isnull(cust_addr, '') address
from customers
Which gives me this in the parameter list:
FIRST OUTPUT - ACTUAL
1 cust1 addr1
2 customer2 addr2
Which is what I expected but I want:
SECOND OUTPUT - DESIRED
1 cust1 addr1
2 customer2 addr2
What I have tried:
select cust_num, rtrim(cust_name) + space(60 - len(cust_name)) +
rtrim(cust_addr) + space(60 - len(cust_addr)) customer
from customers
Which gives me the first output.
select cust_num, rtrim(cust_name) + replicate(char(32), 60 - len(cust_name)) +
rtrim(cust_addr) + replicate(char(32), 60 - len(cust_addr)) customer
Which also gives me the first output.
I have also tried replacing space() with char(32) and vice versa
I have tried variations of substring, left, right all to no avail.
I have also used ltrim and rtrim in various spots.
The reason for the 60 is that I have checked the max length in both fields and it is 50 and I want some whitespace between the fields even if the field is maxed. I am not really concerned about truncated data since the city, state, and zip are in different fields so if the end of the street address is chopped off it is ok, I guess.
This is not a show stopper, the SSRS report is currently deployed with the first output but I would like to make it cleaner if I can.
Whammo blammo (for leading spaces):
SELECT
RIGHT(space(60) + cust_name, 60),
RIGHT(space(60) + cust_address, 60)
OR (for trailing spaces)
SELECT
LEFT(cust_name + space(60), 60),
LEFT(cust_address + space(60), 60),
The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.
SELECT CAST('Test' AS CHAR(20))
This returns the value 'Test '.
This is based on Jim's answer,
SELECT
#field_text + SPACE(#pad_length - LEN(#field_text)) AS RightPad
,SPACE(#pad_length - LEN(#field_text)) + #field_text AS LeftPad
Advantages
More Straight Forward
Slightly Cleaner (IMO)
Faster (Maybe?)
Easily Modified to either double pad for displaying in non-fixed width fonts or split padding left and right to center
Disadvantages
Doesn't handle LEN(#field_text) > #pad_length
Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.
Also, this allows for padding a field to the maximum length of its contents.
WITH
cte AS (
SELECT 'foo' AS value_to_be_padded
UNION SELECT 'foobar'
),
cte_max AS (
SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;
declare #t table(f1 varchar(50),f2 varchar(50),f3 varchar(50))
insert into #t values
('foooo','fooooooo','foo')
,('foo','fooooooo','fooo')
,('foooooooo','fooooooo','foooooo')
select
concat(f1
,space(max(len(f1)) over () - len(f1))
,space(3)
,f2
,space(max(len(f2)) over () - len(f2))
,space(3)
,f3
)
from #t
result
foooo fooooooo foo
foo fooooooo fooo
foooooooo fooooooo foooooo

Delete last N characters from field in a T-SQL Server database

I have table of over 4 million rows and accidentally in one column there is more data than needed.
For example instead of ABC there is ABC DEFG.
How can I remove that N symbols using TSQL? Please note that I want to delete this characters from database, NOT just select substring. Thank you
UPDATE mytable SET column=LEFT(column, LEN(column)-5)
Removes the last 5 characters from the column (every row in mytable)
I got the answer to my own question, ant this is:
select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))
Where N is the number of characters to remove. This avoids to write the complex column/string twice
You could do it using SUBSTRING() function:
UPDATE table SET column = SUBSTRING(column, 0, LEN(column) + 1 - N)
Removes the last N characters from every row in the column
This should do it, removing characters from the left by one or however many needed.
lEFT(columnX,LEN(columnX) - 1) AS NewColumnName
You can use function RIGHT [https://www.w3schools.com/sql/func_sqlserver_right.asp]
RIGHT( "string" , number_of_chars_from_right_to_left)
That should look like this:
Query: SELECT RIGHT('SQL Tutorial', 3) AS ExtractString;
Result: "ial"

Resources