MSSQL Insert Data From One Table To Another With Fixed Value - sql-server

Hello I would like to insert in a table called Data multiple columns from another table called SourceTable and one colum that has a standar value for every row added in Data.
Assume that you have Column1 and Column2 in the table called SourceTable and source_id is precalculated and it will be the same for every row added into Data on this query.
INSERT INTO Data (Columns1, Column2, source_id)
SELECT Column1, Column2
FROM SourceTable
UNION SELECT 2;
I tried this one but is not working, most likely because the SELECT 2 returns only one row.

Your issue is that you're giving SQL 3 columns to insert 2 values into, if source_id is going to be 2 as your union selects then you'd want something like this;
INSERT INTO Data (Columns1, Column2, source_id)
SELECT Column1, Column2, 2
FROM SourceTable
The number of columns you're inserting needs to match the number of columns that you're inserting to. The way you were doing it would have produced this result;
Column1 Column2 source_id
Value1 Value2
2
but even the union would have failed as the queries that you're unioning need to have the same number of columns.

Related

Union all in snowflake

I'm using union all in my code but one of the tables contains a column that the other one doesn't, how can I insert that column in the output, I don't wanna add it in the table itself.. I need that column to be there and the number of columns should be the same from both tables
Thanks
The normal way to deal with this is to pad the short query with 'dummy' columns.
Suppose TABLE1 has four columns called COL1, COL2, COL3 and COL4.
The TABLE2 3 called COLA, COLB and COLC.
SELECT
COL1
,COL2
,COL3
,COL4
FROM TABLE1
UNION
SELECT
COLA
,COLB
,COLC
,NULL -- or empty string or zero or any padding value compatible with the data-type of COL4.
FROM TABLE2 ;
The results should have 4 columns (COL1 thru COL4) because the column names are taken from the first query.
This practice of padding out data structures to the same signature is common in Databases when combining related but different types and I know it as The Battenberg Manoeuvre.

Inserted less records than selected

I have a simple SQL insert on Snowflake:
insert into table(
column1,
column2,
column3,
column4,
column5)
select
substring(data_string,1,3),
substring(data_string,4,3),
substring(data_string,7,3),
current_timestamp,
'1'
from table1
Select gives me ~690K records but it inserts only ~334K records. When I delete ~200K records from table it still inserts less.
There are no duplicates.
Columns are the right size.
I am not able to post the data because of the security.
So I am just asking if someone had the similar problem and the solution?

SQL Query to return rows with the most columns populated

Azure SQL Server 2019.
We have a table Table1 with over 100 columns of differing types of nvarchar data, all of which are allowed NULL values, and where there could be anywhere from 1 to 100 columns populated in a given record. I need to formulate a query that returns the rows ranked by how many columns have values in them, in descending order.
I started going down a road of using DATALENGTH and having to type out the name of every single column, but I can only imagine there has to be a more efficient way. Assuming the column names are column1, column2, column3 etc, how would I accomplish this?
How about a lateral join that unpivots the columns to rows? This requires enumerating the columns just once, like so:
select t.*, c.cnt
from mytable t
cross apply (
select count(*) cnt
from (values (t.column1), (t.column2), (t.column3)) x(col)
where col is not null
) c
order by c.cnt desc

Export data from Microsoft SQL Server using a query to target data

I know how to generate scripts to script insert lines allowing me to backup some data. I was wondering though if it was possible to write a query (using WHERE clause as an example) to target a very small subset of data in a very large table?
In the end I want to generate a script that has a bunch of insert lines and will allow for inserting primary key values (where it normally would not let you).
SSMS will not let you to have the INSERT queries for specific rows in a table. You can do this by using GenerateInsert stored procedure. For example :
EXECUTE dbo.GenerateInsert #ObjectName = N'YourTableName'
,#SearchCondition='[ColumnName]=ColumnValue';
will give you similar result for the filtered rows specified in the #SearchCondition
Let's say your table name is Table1 which has columns Salary & Name and you want the insert queries for those who have salary greater than 1000 whose name starts with Mr., then you can use this :
EXECUTE dbo.GenerateInsert #ObjectName = N'Table1'
,#SearchCondition='[Salary]>1000 AND [Name] LIKE ''Mr.%'''
,#PopulateIdentityColumn=1;
If I read your requirement correctly, what you actually want to do is simply make a copy of some data in your table. I typically do this by using a SELECT INTO. This will also generate the target table for you.
CREATE TABLE myTable (Column1 int, column2 NVARCHAR(50))
;
INSERT INTO myTable VALUES (1, 'abc'), (2, 'bcd'), (3, 'cde'), (4, 'def')
;
SELECT * FROM myTable
;
SELECT
*
INTO myTable2
FROM myTable WHERE Column1 > 2
;
SELECT * FROM myTable;
SELECT * FROM myTable2;
DROP TABLE myTable;
DROP TABLE myTable2;
myTable will contain the following:
Column1 column2
1 abc
2 bcd
3 cde
4 def
myTable2 will only have the last 2 rows:
Column1 column2
3 cde
4 def
Edit: Just saw the bit about the Primary Key values. Does this mean you want to insert the data into an existing table, rather than just creating a backup set? If so, you can issue SET IDENTITY_INSERT myTable2 ON to allow for this.
However, be aware that might cause issues in case the id values you are trying to insert already exist.

Duplicate all columns except for some of them

Is there an option to duplicate row in sql server without write all the columns? I just want to write the columns that I want to insert it by myself.
for example:
MYTABLE:
Id|Name|Status|Date
-------------------
2|abca|active|03.10
so I can do:
INSERT INTO MYTABLE (Id, Name, Status, Date )
SELECT NEWID(), "bird", status, Date
FROM MYTABLE
WHERE Id = "2"
it will duplicate the row:
Id |Name|Status|Date
-------------------
2 |abca|active|03.10
fg35|bird|active|03.10
can't I duplicate all columns, except for what I write?
in this example:
something like (pseudo code):
duplicate all columns in MYTABLE where Id="2" except for (id="newID()", name="bird")
No, in SQL Server you either need to provide all values for all columns:
INSERT INTO TableName VALUES(value1, value2, ...)
or provide the columns you want to insert to
INSERT INTO TableName (column1, column2, ...) VALUES(value1, value2, ...)
You cannot achieve what you want in a general sense.
There may be a way to do it in some specific cases buy duplicating all columns and updating some but that will depend on your ability to distinguish the newly inserted row from the previously existing one.

Resources