Creating an UPDATE script in SQL Server 2005 - sql-server-2005

I have a table in SQL Server 2005 filled with data. Is there a method by which I can generate update statements including the data in it?

There's a nice free tool here http://www.lss.co.uk/Products/LiveDataScript/

If you don't find any better solution, try this:
SELECT
'UPDATE [Table] (field1, field2, field3) Values ('
+ field1 + ', '
+ field2 + ', '
+ field3 + ')'
FROM [Table]
I know, not nice.

Go here and get the Microsoft SQL Server Management Studio Express SSMSE Download page
After installing you can then connect to your database with the tool and generate several types of "vanilla" scripts.

If you mean data on the same row, just use it in the Update Statement
Update MyTable Set ColumnA = ColumnB + ColumnC
If you want to use data from other rows, you probably have to join it back to it's self
Update a
Set ColumnA = b.ColumnD
From MyTable a
Join MyTable b on a.ColumnB = b.ColumnC

SELECT
'UPDATE [Table] SET field1 = ' + field1 + ' , field2 = ' + field2 + ' , field3 = ' + field3 + ' WHERE <condition> ' FROM <Table>
Use extra single Quotes wherever string data is updated.

Related

SQL Search for Data in Multiple Columns

Dears,
I have a table as shown below as a sample, and I want to run one query by which i can find all the yellow highlighted ones by using %AAA%.
Instead of running the Where command on each column one by one, I can do one general find option and it will list all the rows.
Thank you in advance!!
You can include all the conditions in one where clause using or:
where col1 like '%aaa%' or
col2 like '%aaa%' or
. . . -- and so on for all the columns
Unpivot the columns and do a WHERE based on that:
select *
from Table
where exists (select 1
from (values (col1), (col2), (col3) ) AS v (allCols) -- etc
where v.allCols like '%aaa%'
);
If you can't be bothered to type them out, try this little query:
select STRING_AGG('(' + c.name + ')', ', ')
from sys.columns c
where c.object_id = OBJECT_ID('Name_Of_Table_Here');
If you are using sql server then you can write dynamic query to do so. Please try below query:
declare #sql as varchar(max);
select #sql = 'select * from [TableName] where '
+ stuff((
select ' or [' + [column_name] + '] like ''%AAA%'''
from information_schema.columns
where table_name = 'TableName'
for xml path('')
)
, 1, 5, ''
);
exec(#sql);
This query will return every row in which at least one column contains AAA.
If you are using PostgreSQL, you can use its JSON functionality:
select t.*
from the_table t
where exists (select *
from jsonb_each(to_jsonb(t)) as x(col,val)
where val like '%AAA%');
If you are using Postgres 12 or later you can use a SQL/JSON path expression:
select t.*
from the_table t
where to_jsonb(t) ## '$.* like_regex "AAA" flag "i"'

SQL Server 2012, Combine multiple fields into one

I've tried
'field1'+'field2'+'field3' as combination
and tried:
((((field_1||'_')||field_2_yes)||'_')||field_3_yes) AS combination
tried:
field1 || field2 as combination
i've also tried Concat, coalesce, can't seem to get it to work.
Also I am querying SQL server through excel if that helps.
Expected output is a column named combination with the field1field2field3 data as the rows within combination column. I'm am not trying to create the literal string field1field2field3 but combine the data from these fields into a string and display in new column.
The issue is with the data types as to why these fields are not combining.
Could you please try without aposthropes?:
select combination = (field1 + field2)
from table
In case you need to put a space between the values, if field1 and field2 is varchar, then you can do:
select combination = (field1 + ' ' + field2)
from table
If field1 and field2 is not varchar, then you can cast like below and use in your main query:
cast(field1 as varchar(50))
So do you want only to display 2 fields as a one field?
Field1 = 'hello'
field2 = 'world'
select field1 + field2 as concatfield from table
select concat(field1, field2) as concatfield from table
This will give you output like that:
helloworld
If you want to add space then try this:
select field1 + ' ' + field2 as concatfield from table
select concat(field1, ' ', field2) as concatfield from table
This will give you output like that:
hello world
And then exacly the same if you want to update a field in DB
update table
set concatfield = field1 + ' ' + field2 --or concat(field1, ' ', field2)
--where 1=1
It is pretty basic
declare #Field varchar(10) = 'value'
select #Field + #Field + #Field as comb
select '#Field' + '#Field' + '#Field' as comp
comb
------------------------------
valuevaluevalue
comp
------------------
#Field#Field#Field

Select from tables, where the table names are stored in another table

I'm trying to write a query in which I can select data from a series of tables. I want to be able to pull those table names FROM ANOTHER TABLE; I don't want to just write
select * from tableA union select * from tableB etc.
A further restriction that's complicating the issue is that my query MUST start with select.
I've tried to use OPENQUERY within the select statement but the server I'm trying to access is 'not configured for DATA ACCESS.'
You can do something like this:
DECLARE #SQL AS VARCHAR(MAX);
SELECT #SQL = COALESCE(#SQL + ' ', '') +
'SELECT * FROM ' + TableName +
CASE
WHEN TableName = MAX(TableName) OVER () THEN ''
ELSE ' UNION ALL '
END
FROM TableNames;
EXEC(#SQL);

concatenate two database columns into one resultset column

I use the following SQL to concatenate several database columns from one table into one column in the result set:
SELECT (field1 + '' + field2 + '' + field3) FROM table1
When one of the fields is null I got null result for the whole concatenation expression. How can I overcome this?
The database is MS SQL Server 2008. By the way, is this the best way to concatenate database columns? Is there any standard SQL doing this?
The SQL standard way of doing this would be:
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1
Example:
INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;
helloworld
If you were using SQL 2012 or above you could use the CONCAT function:
SELECT CONCAT(field1, field2, field3) FROM table1
NULL fields won't break your concatenation.
#bummi - Thanks for the comment - edited my answer to correspond to it.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
If you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:
SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1
http://www.codeproject.com/KB/database/DataCrunching.aspx
Use ISNULL to overcome it.
Example:
SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1
This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.
If both Column are numeric Then Use This code
Just Cast Column As Varchar(Size)
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
Just Cast Column As Varchar(Size)
If both Column are numeric then use code below.
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
What will be the size of col3 it will be 40 or something else

View error in PostgreSQL

I have a large query in a PostgreSQL database.
The Query is something like this:
SELECT * FROM table1, table2, ... WHERE table1.id = table2.id...
When I run this query as a sql query, the it returns the wanted row.
But when I tries to use the same query to create a view, it returns an error:
"error: column "id" specified more than once."
(I use pgAdminIII when executing the queries.)
I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?
That happens because a view would have two id named columns, one from table1 and one from table2, because of the select *.
You need to specify which id you want in the view.
SELECT table1.id, column2, column3, ... FROM table1, table2
WHERE table1.id = table2.id
The query works because it can have equally named columns...
postgres=# select 1 as a, 2 as a;
a | a
---+---
1 | 2
(1 row)
postgres=# create view foobar as select 1 as a, 2 as a;
ERROR: column "a" duplicated
postgres=# create view foobar as select 1 as a, 2 as b;
CREATE VIEW
If only join columns are duplicated (i.e. have the same names), then you can get away with changing:
select *
from a, b
where a.id = b.id
to:
select *
from a join b using (id)
If you got here because you are trying to use a function like to_date and getting the "defined more than once" error, note that you need to use a column alias for functions, e.g.:
to_date(o.publication_date, 'DD/MM/YYYY') AS publication_date
No built-in way in the language to solve it (and frankly, * is a bad practice in general because it can cause latent defects to arise as the table schemas change - you can do table1.*, table2.acolumn, tabl2.bcolumn if you want all of one table and selectively from another), but if PostgreSQL supports INFORMATION_SCHEMA, you can do something like:
DECLARE #sql AS varchar
SELECT #sql = COALESCE(#sql + ', ', '')
+ '[' + TABLE_NAME + '].[' + COLUMN_NAME + ']'
+ CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN ('table1', 'table2')
ORDER BY TABLE_NAME, ORDINAL_POSITION
PRINT #sql
And paste the results in to save a lot of typing. You will need to manually alias the columns which have the same name, of course. You can also code-gen unique names if you like (but I don't):
SELECT #sql = COALESCE(#sql + ', ', '')
+ '[' + TABLE_NAME + '].[' + COLUMN_NAME + '] '
+ 'AS [' + TABLE_NAME + '_' + COLUMN_NAME + ']'
+ CHAR(13) + CHAR(10)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME IN ('table1', 'table2')
ORDER BY TABLE_NAME, ORDINAL_POSITION