How to update certain columns in table to truncate records after certain length and regex replace string? - sql

I have a list of columns in a table that I want to truncate to 255 records max and remove any percent signs from the columns, how would I do this?
old Table
col1 col2
adfaadfadfadfdfdafdjf;kldjf;adjsfjads;f 60%
new Table
col1 col2
adfaadfadfadf 60
col1 is not representative of the full string only used for illustration purposes.
I am using sql server 2012.
code so far:
SELECT
case
when len(col)=255
then left(col, 255)
else col end col
from table

Is this not as simple as...?
UPDATE YourTable
SET StringColumn = LEFT(StringColumn,255),
PercentColumn = REPLACE(PercentColumn,'%','')
GO
--You then probably want to fix that column's datatype.
ALTER TABLE YourTable ALTER COLUMN PercentColumn int; --Assuming integer values only.

Related

SQL Server insert into next column

SQL Server 2012: is it possible to do a insert into select statement but insert data into the next column if the previous is already populated?
I have a table with a number of columns to store dates, I want to take data from another table and insert into the next available null date column.
If you are saying that the previous column is already populated, then you're really looking for some sort of update. Try this:
UPDATE yourTable
SET
col1 = CASE WHEN col1 IS NULL THEN 'value' ELSE col1 END,
col2 = CASE WHEN col1 IS NOT NULL THEN 'value' ELSE col2 END;
The logic here is what you described, namely that we attempt to update col1 with some value. Should that column be empty, we make the update, otherwise we update col2 instead.

store query result, with multiple results as list variable to use later

I want to put the results of a select statement into an #variable to use later on in the query. I dont know how many results there are going to be.
I have tried;
SET #variable = SELECT column FROM table
RESULT
#variable=( 123213,321312,321321)
I want to then use the results as
UPDATE table SET column=1 WHERE column in #variable
Just use a temporary table:
SELECT column
INTO #tmp
FROM table;
UPDATE table
SET column = 1
WHERE column in (SELECT column FROM #tmp);
You can also use a table variable but that requires specifying the types of the columns to define the variable.
If you really want it to be in the form of a variable (available only at execution time), then you can declare a TABLE variable.
DECLARE #variable TABLE (Column1 INT);
INSERT INTO #variable
SELECT Column FROM Table
The better way would be to create a temporary table with SELECT INTO:
SELECT Column
INTO #variable
FROM table;
The you can use the #variable or #variable as a regular table in any query.
UPDATE table
SET Column = 1
WHERE column IN (SELECT COLUMN FROM #variable)
or
UPDATE table
SET Column = 1
WHERE column IN (SELECT COLUMN FROM #variable)
Although I would prefer / recommend the JOIN style:
UPDATE t
SET column = 1
FROM table t
INNER JOIN #variable v on t.column = v.column
There are numerous reasons why I don't recommend using a table variable but one of the most important is for performance reasons.
The Query Optimizer will always generate an estimate of 1 for when reading data from a table variable, which will generate a less than optimal execution plan for the scenario in which #variable has a large number of rows.
If you are dealing with multiple values then you should be using TABLE VARIABLE
Something like.......
Declare #t TABLE (Value INT)
INSERT INTO #t (Value)
SELECT column FROM table
Now use this Table variable in your update , something like.....
UPDATE table
SET column=1
WHERE column in (Select Value from #t)
But why cant you just simply select from the table directly when updating records, why do you even need to put it into any kind of variable anyway
UPDATE table
SET column=1
WHERE column in (SELECT column FROM table)
OR better way of doing this would be something like.....
UPDATE t1
SET t1.column=1
FROM table1 t1
INNER JOIN Table2 ON t1.Column = t2.column

Add columns dynamically based on a condition in SQL

I'm using SSMS 2012. Consider a table A with columns A, B, C. I would like to dynamically add a new column, D to this table based on a condition in one of the existing columns. How can this be achieved?
Query looks like the following,
select col1, col2 from #temptbl
To this #temptbl, I would like to add a column, col3 and the value in col3 is based on a condition on col2.
To add a column, you need to ALTER the table
Let say you want to add an integer for COL3
ALTER TABLE #temptbl
ADD col3 INTEGER
And to update the value in col3 based on a condition on col2, you need to do an UPDATE and use a CASE statement to check the condition :
Let say you want to set value 3 in COL3 if COL2 is equal to 2
UPDATE #temptbl
SET col3 = CASE WHEN col2 = 2 THEN 3 ELSE null END
After your edit it is still incredibly vague what you want to do but maybe this is close??? No idea what the condition or the output should be but when the condition is not met the output of this will be NULL.
select col1
, col2
, case when SomeCondition then SomeValue end as Col3
from #temptbl
Like Tom mentioned, you can only had a column for the whole table, not on a conditional basis. You can make it a computed column or when you query the table, have a CASE statement if adding a column is not possible.

sql query to truncate columns which are above specified length

I have the following table in postgres:
create table1 (col1 character varying, col2 character varying);
My table has the following data:
col1 col2
Questions Tags Users
Value1 Value2 Val
I want find the length of col1 and col2 and when the length of values of column 1 and column2 exceeds 6, I want to truncate it and discard the remaining values. i.e. I want my final table to look like the following:
col1 col2
Questi Tags U
Value1 Value2
Actually the reason why I want to do this is, when I create index on table1 then I am getting the following error:
ERROR: index row size 2744 exceeds maximum 2712 for index "allstrings_string_key"
HINT: Values larger than 1/3 of a buffer page cannot be indexed.
Consider a function index of an MD5 hash of the value, or use full text indexing.
I know I can do this by importing the values to some programming language and then truncating the value. Is there some way by which I may achieve the same using an sql query in postgres.
Couldn't you just update them to contain only strings of length 6 at max?
I am no postrgres pro, so this is probably not the best method, but should do the job anyways:
UPDATE table1 SET col1 = SUBSTRING(col1, 1, 6) WHERE LEN(col1) > 6
UPDATE table1 SET col2 = SUBSTRING(col2, 1, 6) WHERE LEN(col2) > 6
I'd suggest that you actually follow the advice from Postgres, rather than changing your data. Clearly, that column with a 2k character long string shouldn't be indexed -- or not with a btree index anyway.
If the idea behind the index is searching, use full text search instead:
http://www.postgresql.org/docs/current/static/textsearch.html
If the idea behind the need is for sorting, use a functional index instead. For instance:
create index tbl_sort on (substring(col from 1 for 20));
Then, instead of ordering by col, order by substring(col from 1 for 20).
Have you tried changing the type of the column to CHAR instead of VARCHAR?
ALTER TABLE table1
ALTER COLUMN col1 SET DATA TYPE CHAR(6),
ALTER COLUMN col2 SET DATA TYPE CHAR(6)
If you need the column to be variable length, you can specify a limit (note that this is a PostgreSQL extension):
ALTER TABLE table1
ALTER COLUMN col1 SET DATA TYPE CHARACTER VARYING(6),
ALTER COLUMN col2 SET DATA TYPE CHARACTER VARYING(6)

Can I set a formula for a particular column in SQL?

I want to implement something like Col3 = Col2 + Col1 in SQL.
This is somewhat similar to Excel, where every value in column 3 is sum of corresponding values from column 2 and column 1.
Have a look at Computed Columns
A computed column is computed from an
expression that can use other columns
in the same table. The expression can
be a noncomputed column name,
constant, function, and any
combination of these connected by one
or more operators.
Also from CREATE TABLE point J
Something like
CREATE TABLE dbo.mytable
( low int, high int, myavg AS (low + high)/2 ) ;
Yes, you can do it in SQL using the UPDATE command:
UPDATE TABLE table_name
SET col3=col1+col2
WHERE <SOME CONDITION>
This assumes that you already have a table with populated col1 and col2 and you want to populate col3.
Yes. Provided it is not aggregating data across rows.
assume that col1 and col2 are integers.
SELECT col1, col2, (col1 + col2) as col3 FROM mytable