Create an insert script from select results - ssms

Using SQL Server Management Studio is there a way I can select one or more rows in the grid of select results and have SQL Server Mangement Studio generate one or more insert statements (one for each row selected) which would insert that data into a table with the same schema?
Edit: I know how to create one manually, but I was hoping there would be something that would create it automatically for me. If you are familiar with Toad there is a way to have Toad generate inserts based on data in the results pane and I was hoping SSMS had an equivalant function.

Try to save the query result into a disposable table.
For example:
SELECT * INTO disposable_customer_table FROM customer_table WHERE id IN (in range of something)
Then do a db -> Tasks -> Generate Scripts.
Select specific database objects.
Choose disposable_customer_table from the list of table names.
Choose Save to file.
Make sure to do an Advance setup and select "Data only" from the 'Types of data to script'.
Tweak the result file and rename the disposable_customer_table back to the original table name.
Clean it up and drop the disposable_customer_table.

select 'insert into tableB values (', tableA.x ,',',tableA.y,',',tableA.z,')' from tableA

I think you have two options here:
Create your inserts manually. For instance:
select Name, Surname,
'insert into Person (Name,surname) values ('''+Name+''','''+Surname+')'
from Person
This gets you the results and, in the last column, the insert script for the row. You can then select and paste it in an Editor window.
Right click on the db -> Tasks -> Generate Scripts. Press then Advance and select "Data Only" (Default is Schema Only).

Perform your query and right click on the blank area where the column headers meet the row number in the Results view.
You can then select Script Grid Results:

Related

How to write MERGE query using SELECT FROM VALUES in BigQuery?

I want to write MERGE query using literal values in BigQuery database.
I tried this: https://stackoverflow.com/a/35659674/5659025 (version for SQL Server) but BigQuery returns the error: "Table-valued function not found"
Is it possible to make it in BigQuery and how?
After our discussion in the commet section, I can suggest you two options:
First, using the INSERT statement. According to the documentation:
Use the INSERT statement when you want to add new rows to a table.
Therefore, you modify the rows in your source table. I have used a dummy data to reproduce it. My source data base was:
In the BigQuery UI, the syntax is as follows:
insert `source_table` (email, content)
select "ale#gmail.com" as email, "add something" as content
or
insert `source_table` (email, content)
select "ale#gmail.com" , "add something"
Notice that I used double quotes because the field I am adding is a String. And the output is as below:
The Second option is to use UNION ALL. I would like to point that with this option your are not updating or modifying your source table, instead you are creating a view with new data added. The syntax is as below:
SELECT 'aleee#gmail.com' , "add something 2" UNION ALL
--#if you want to add more rows to your view, you will need to write another
--#select 'email#gmail.com.br', "something " UNION ALL
SELECT * FROM `test-proj-261014.sample.foobar`
I hope it helps.

sql server shortcut for select statement writing

Many times a day I have to write similar queries to get single record:
select t.*
from some_table t
where t.Id = 123456
maybe there is some shortcuts for retrieving single record? Like entering id, table and SQL server generates rest code automatically
In Sql Server Go to
Tools-> Options-> Environments->Keyboard
You will get shortcuts, there you can define your own as well as get the standards.
you can set a short cut for a fully executable query like
select * from table where id =20
but not like below
select * from

SQL using REPLACE on one of many columns

I have the following query:
SELECT * FROM MailingList
There are about 20+ columns in the MailingList table, one which is called Address. This column has some fields which contain commas, which I need to take out. So I updated my query to:
SELECT REPLACE(Address, ',', '') AS Address, * FROM MailingList
But now I have two Address columns. Is there a way to only display one Address column while still using the wildcard (*) for all the other columns?
There is not a way to do this, though listing the columns you want explicitly is a good idea anyway.
You can trick as following query:
Get the data into a temp table
Drop the cloumns that are not needed
Get results and drop temp table
SELECT *, REPLACE(Address, ',', '') AS Address2
INTO #TempTable
FROM MailingList
ALTER TABLE #TempTable
DROP COLUMN [Address]
SELECT * FROM #TempTable
DROP TABLE #TempTable
I agree with Shadow - avoid using the * wild card if you can...
I know listing out ALL of the columns in select statement for big tables is a pain so here is a quick short cut you may not be aware of: In SQL Server Management Studio, browse through the object explorer and find the table you want to select from (MailingList). Right-click it to view the context menu and choose "Script Table as" then "SELECT TO" then "New Query Editor Window". This will create a new select statement with each column spelled out. In the future, use this method to create select statements, queries, procedures, etc. rather then the * wildcard. Performance is better and it just looks nicer :-)
Then you can solve your alias issue with the replace function.

Pentaho Kettle Spoon Date manipulation

I am using Pentaho Spoon to do some transformation. I am using 'Table Input' and joining multiple tables to get final output table.
I need to achieve:
SELECT COUNT(distinct ID)
FROM TBLA join TBLB ON TBLA.ID=TBLB.ID
WHERE
TBLA.ID=334
AND TBLA.date = '2013-1-9'
AND TBLB.date BETWEEN '2012-11-15' AND '2013-1-9';
I am manually inserting '2012-11-15' but I am using Get System Data to insert '2012-1-9'. I am using 1 Get System Data.
My query is:
SELECT COUNT(distinct ID)
FROM TBLA join TBLB ON TBLA.ID=TBLB.ID
WHERE
TBLA.ID=334
AND TBLA.date='?'
AND TBLB.date BETWEEN '2012-11-15' AND '?';
I get error message in Table Input saying No value specified for parameter 2
Any suggestion will be appreciated.
Thank you.
Simple one this; You need to "duplicate" the system date. So add another line in "get system data" called "date2" or something, make it the same as the first line, and then it will fill in the 2nd parameter or ?
OR simply change the query to say between '2012-11-15' and TBLA.date
then you dont need the 2nd parameter
Personally I prefer the pattern of a Get System Info/Add Constants step to create one row with multiple columns that feeds into a Database Join step. Then you replace parameters in your query with columns instead of rows, and you can specify a column more than once.

SQL Server 2008 column select

In SQL Server, if I got a table with like 20 columns and I want 18 of them, can I say something like * minus columnname1, columnname2, course right now I write them all.
But if you could it would be much easier.
Little hint to replace the asterisk with column names in SQL Management Studio in no time without any fancy plugin:
Select your written query (no matter how many joins, etc.)
Right click and select "Design Query in Editor..."
Simply click "Ok"
The asterisk should have been expanded to column names now :)
Ofc it's possible to select/deselect any column in the query editor..
Hth
It is not possible. However if you are using SQL Server Management Studio 2008 / 2005 you can right click on the table and select the "Script Table as > SELECT To" menu option. This will save you typing the column names, or purchase Red-Gate's SQL Prompt
Out of the box - no, it's not possible. You have to spell out all the columns you want explicitly.
With SQL Server Management Studio 2008, there is intellisense which can help you select columns from a table - so that's certainly one step to help ease the pain.
Add-in tools like SQL Prompt offer more help - in SQL Prompt, you can type
SELECT *
FROM dbo.YourTable
and if you have the cursor just after the asterisk symbol (*), you can press <TAB> and expand the asterisk into the list of all columns for that table (and then remove the two you don't want) - or you can popup a window and pick those columns you really want.
Very handy, very useful, very much speeding up development - but it's not a free tool.....
You can use select TOP (18) * from givenTable is you want 18 rows.
There is no such method for columns. In fact column names are stored in master db and you can extract them and consruct query looking like what you are asking for BUT it would not be easier than just select field1,field2 ... field18 from blaBlaBla.
SELECT table_name=sysobjects.name,
column_name=syscolumns.name,
datatype=systypes.name,
length=syscolumns.length
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U'
and sysobjects.name='myTableName'
ORDER BY sysobjects.name,syscolumns.colid
will give you the list of your columns. You can write select generator based on this query.
I'd like to add to the answer of, "No, it's not possible directly in SQL". I would love to have that feature too! It sucks when you're trying to do some quick debugging on a 10+ column table that has a varbinary(max).
But I really just want to point out an alternative to Kane's tip for SSMS 2008 (Sql Server Management Studio).
If you open the Object Explorer (right-click in the query window and choose "Open Server in Object Explorer"), navigate to the node for the table in question. Expand the node so you can see the "Columns" node. Now "drag" the Columns node over to your query window and "drop" it. It will paste in all the column names for the table--and you can use it directly in a SELECT clause.
It is not possible as far as I know.
I have created a script for easy copy/pasting multiple columns, you might find it useful. See:
http://www.sqlservercentral.com/scripts/102375/
The script is explained in detail there, but in short for those who do not have an account on sqlservercentral:
It's a stored procedure that i can run using a shortcut. Type in your tablename (also works with temp tables and views), highlight it, hit the shortcut and it will display the columns of the table. From there you can easily copy multiple columns (the columns are also shown with a comma in front of the column name, so that also saves you some typing) and paste it in your query screen.
CREATE PROCEDURE [dbo].[sp_ColumnSelect]
#FullObjectName varchar(200)
AS
/*
Author: Robin van Schaik
Version: 1.3 (03-OCT-2012)
*/
DECLARE #Object varchar(200)
DECLARE #Schema varchar(200)
DECLARE #Database varchar(200)
DECLARE #IsTempTable bit
-- Break down parameter in Database/Schema/Object
SET #Object = PARSENAME(#FullObjectName,1)
SET #Schema = ISNULL(PARSENAME(#FullObjectName,2),'dbo')
SET #IsTempTable = case when left(#Object,1)='#' then 1 else 0 end
SET #Database = case when #IsTempTable=1 then 'tempdb' else PARSENAME(#FullObjectName,3) end
EXEC(
'SELECT
b.Name as ColumnStart
, '',''+b.Name as ColumnNext
, ''[''+b.Name+'']'' as ColumnStartBr
, '',[''+b.Name+'']'' as ColumnNextBr
FROM
' +#Database+'.sys.objects a
INNER JOIN
' +#Database+'.sys.columns b
ON a.object_id=b.object_id
INNER JOIN
' +#Database+'.sys.schemas d
ON a.schema_id=d.schema_id
WHERE
a.Object_ID=OBJECT_ID('''+#Database+'.'+#Schema+'.'+#Object+''')
AND d.name = '''+#Schema+'''
'
)