Get columnnames as string sepparated by comma / list - sql

i am doing some inserts with some of my tables and all fields but a few need to be inserted or updated. Like here.
Is there a quick way to get the columns of a table returned as a string so i can copy them into my sql query?
For example i have a table:
create table myTable1
(
column1 integer not null,
column2 integer not null ,
column3 integer not null,
column4 integer not null,
column5 integer not null,
...a lot more fields...
)
And later i want to insert something from another table myTable2 that has the same fields (dont question my ways and why i have two identical tables).
INSERT INTO myTable SELECT column1, column2, column3, column4, ...
FROM table_source
But the tables have so many fields it is cumbersome to write them donw manualy and it would be faster to have a string where i can just delete the column names i dont need. Is there a nice query that ouputs "column1, column2, column3, column4, ..." so i dont have to write that myself and can copy tha into my query?

Found the answer quickly.
SELECT table_catalog, string_agg(column_name, ', ')
FROM information_schema.columns
WHERE table_schema = 'mySchema'
AND table_name = 'myTable' GROUP BY 1;
This query does the trick for me.

Related

Copy existing table with NULLABLE column [duplicate]

When I create a temp table using a select into in SQL Server, is there a way to specify that a column should be nullable? I have a multi-step process where I'm making a temp table by selecting a lot of columns (which is why I'm not doing a create table #tmp (...)). After I make that temp table, I'm updating some columns and some of those updates might null out a field.
I know I could do an alter table alter column statement to achieve what I want, but I'm curious about whether there's a way to specify this in the select itself. I know you can inline cast your columns to get the desired datatype, but I can't see how you specify nullability.
Nullability is inherited from the source column.
You can lose or gain nullability with an expression:
Example (constant literals appear to be problematic - need a good NOOP function which can return NULL):
CREATE TABLE SO5465245_IN
(
a INT NOT NULL
,b INT NULL
) ;
GO
SELECT COALESCE(a, NULL) AS a
,ISNULL(b, 0) AS b
,COALESCE(10, NULL) AS c1
,COALESCE(ABS(10), NULL) AS c2
,CASE WHEN COALESCE(10, NULL) IS NOT NULL THEN COALESCE(10, NULL) ELSE NULL END AS c3
INTO SO5465245_OUT
FROM SO5465245_IN ;
GO
SELECT TABLE_NAME
,COLUMN_NAME
,IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'SO5465245%'
ORDER BY TABLE_NAME
,ORDINAL_POSITION ;
GO
DROP TABLE SO5465245_IN ;
GO
DROP TABLE SO5465245_OUT ;
GO
This soulution I've recently come up with and though I should share:
select top 0
B.*
into
TargetTable
from
SourceTable as A
left join SourceTable as B on 1 = 0
This effectively creates a duplicated structure of SourceTable in TargetTable with all columns nullable (at least in sql2008).
CONVERT will make your columns nullable, and works for literals/constants too. Tested in SQL Server 2005/2008.
SELECT
SomeText = CONVERT(varchar(10), 'literal'),
SomeNumber = CONVERT(int, 0)
INTO SO5465245
INSERT SO5465245 VALUES (null, null)
SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'SO5465245'
ORDER BY TABLE_NAME, ORDINAL_POSITION
DROP TABLE SO5465245
If you want to inherit nullablity for the destination column irrespective of the source table columns you can follow this query.
SELECT COLUMN1, COLUMN2, COLUMN3 INTO DestinationTable from SourceTable
if this was your query where COLUMN1,COLUMN2,COLUMN3 were not nullable in SourceTable then change the query as
SELECT NULL COLUMN1, NULL COLUMN2, NULL COLUMN3 INTO DestinationTable from SourceTable
so, this will allow you to insert null values in to the Destination table.
I recently had the same issue - I wanted to use "select into", wanted all columns in the target table to be nullable & a repeatable approach where I didn't have to know the names of the fields in the source table.
select *
into dbo.I_Data
from
(select 1[Z_1]) A
full join (select null[Z_2], * from dbo.S_Data) B on A.Z_1 = B.Z_2
where
dbo.S_Data is the source data table and
[Z_1] & [Z_2] are two dummy columns used for the join
Then to clean up:
(a) Remove the row of nulls
delete dbo.I_Data where [Z_1] = 1
(b) Remove the dummy fields:
alter table dbo.I_Data
drop column [Z_1], [Z_2]
Regards.

Insert data into table with values inside quotes of another select statement

I am trying to insert data into multiple columns of a table with specific values. However one varchar column will have its data value coming from another table select statement placed inside a quotes.
I need it placed inside without having the sub select statement interpreted as part of the string. Below is my query;
INSERT INTO Table1
(column1,
column2,
column3,
column4)
VALUES (484640,
4,
1,
'<HTML><Head></Head><Body>Upload results</Body></HTML>')
Currently your select query will be just treated like a string since it is enclosed within single quotes. The query will be inserted into the column, not the result.
Here is the correct way:
INSERT INTO Table1
(column1,
column2,
column3,
column4)
SELECT DISTINCT 484640,
4,
1,
'<HTML><Head></Head><Body><a href="cgroup-histstatus.aspx?Staging_PKID='
+ cast(column_1 as varchar(50))
+ '">Upload results</a></Body></HTML>'
FROM Table_2
If you want the values from column_1 to be enclosed within single quotes then replace '+ column_1 +' with '''+ column_1 +'''.
This works even when select query returns more than one record.

INSERT INTO subtract 2 values

Is it possible for an INSERT query to subtract 2 values you have entered to create a 3rd value that can then be inserted into a table - if that makes sense...
e.g.
INSERT INTO table1 (column1, column2, column3)
VALUES ('50', '25', column1 - column2)
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', column1 - column2) from table1 where conditions)
This is a sample query! hope it helps!
Convoluted:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
(select 50 as column1,
25 as column2
) t
Since you can't reference other columns from the same SELECT clause, you have to do it as a subquery. I've also switched to using int literals rather than strings, because I can't make subtraction make sense in my head otherwise.
You could also do it using a Table Value Constructor:
INSERT INTO table1 (column1,column2,column3)
select column1,column2,column1-column2
from
( VALUES (50, 25)
) AS t (column1, column2);
As indicated in my comment though, if the relationship should always hold, I'd build table1 as:
CREATE TABLE table1 (
column1 int not null,
column2 int not null,
column3 as column1 - column2
--More columns
)
Because that way, the column3 value is always correct.
You can create function that subtracts values and use this function in insert. This is the right way to do such things:
INSERT INTO table1 (column1, column2, column3)
(select ('50', '25', your_function() ) from table1 where conditions)
/
Using the "INSERT INTO" would do this:
INSERT INTO Table1Name (column1, column2, column3,)
(select 'X', 'Y', X - Y as Z)
Here is a link to SQL Authority with more examples of INSERT INTO
Another method would to be add a trigger to the table, where on insert of data, the third column would be updated with the difference of the first two columns.

insert into with select + new information

I'm trying to write a sql query that can copy specific columns from a table and insert it in the same table + extra information for the other columns
Simply copying certain information would be something like this:
INSERT INTO table (column1, column2)
SELECT column1, column2
FROM table
WHERE columnx = 'some value'
But I need to also insert some new information in column3. How can I do that?
I have the information that will go in "column3", I don't have to get it from an other table or source.
This is for a repeat appointment where basically all the information is the same except for date, planner and appointment_id.
If you know what the values are . . .
INSERT INTO table (column1, column2, column3)
SELECT column1, column2, <value for column3>
FROM table
WHERE columnx = 'some value'

Sql Query Create a new Table

Can anyone offered syntax for a sql query that takes an already created table and inserts some of the data into a new table with a new id(primary key)? So far I tried this
SELECT ((ID INT IDENTITY(1,1) PRIMARY KEY), column1, column2, column3)
INTO table_name
FROM table_name
I keep coming up with a syntax error.
SELECT column1, column2, column3
INTO table_name_new
FROM table_name_old
use like this
INSERT INTO newtable (column1, column2, column3)
SELECT (column1, column2, column3)
FROM table_name
INSERT INTO new_table
(Column1, Column2 . . . )
SELECT Column1, Column2 FROM old_table
Don't include the identity column (the primary key with the auto-generated numbers) in the insert list.
Just make it like below, Aa new id will be automatically created while inserting the record
insert into table1 (col1,col2,col3) select col1,col2,col3 from table2;
According to the documentation on MSDN, the IDENTITY property will transfer through with a SELECT INTO clause, but constraints will not. That means you can create a new table with an IDENTITY column if you include the original IDENTITY column from your source table, but the column in the new table won't be a primary key.
The sane way to do this is to use ALTER TABLE after the table is created, as #Kai has suggested.