Insert Into Selected Table name - sql-server

I would like to do something like this in SQL Server:
INSERT INTO(Here I have SELECT which return Table name) (col1, col2, col3)
VALUES (a, b, c)
I build table name by using the Select statement and I would like to insert some values into this table.
Is it possible to do?

you can do with dynamic SQL
declare #table varchar(100),#sqlst varchar(max)
select #table=tablename from tables
set #sqlst ='insert into '+ #table +'(1,2,3) values(''a'',''b'',''c'')'
exec(#sqlst)

You can do this via a dynamic query like below
DECLARE #Q nvarchar(MAX)
SELECT #Q=N'INSERT INTO '+ tablename +N' (1,2,3) values(''a'',''b'',''c'')' FROM SomeTable
EXEC(#Q)
Please note that since alphanumeric values like a,b,c need to be inserted with single quotes, you'll have to escape the single quotes by another quote

Related

SQL: I want to extract data from second table. As column names of second table matches with values Separated by comma of first table column

I have a table1 with one column with values seperated by comma firstname,lastname. I have a table2 with two column names firstname and lastname, which match with table1's single column values(firstname,lastname). My necessity is I want to extract data from table2 by using select statement SELECT firstname,lastname FROM table2. I used variables to write query.
I transferred values of table1(firstname, lastname) to #link variable and this operation completed successfully. But when i tried to add SELECT #link FROM table2 to the query i thought i would get data of firstname and lastname of table2, But result showing a seperate no column name and value in that column as firstname,lastname.
Tons of Thanks for any help!
declare #link nvarchar(max)
select #link = (select [column]
from [dbo].[table1])
from [dbo].[table2]
SELECT #link FROM table2
You appear to be attempting "dynamic sql", i.e. you build a string that contains a select statment, then execute that string as a query. Conventionally you will find many example that use #sql for this, and the basic fom of this is as follows:
declare #sql nvarchar(max)
select #sql = N'select [column] from [dbo].[table1]'
EXEC sp_executesql #sql;
Note that the #sql contents has to be valid sql syntax. On this point your code contains 2 from clauses and that is NOT valid, plus it isn't clear what you intended, perhaps it was meant to be a join.
declare #sql nvarchar(max)
select #sql = N'select t.[column], j.[column2]
from [dbo].[table1] as t
inner join [dbo].[table2] as j on t.id = j.fk'
EXEC sp_executesql #sql;

How to avoid bulk data duplicate values when insert in to a table in SQL Server 2012

The problem im trying to solve is about avoiding duplicate data getting into my table. I'm using xml to send bulk data to a stored procedure. The procedure I wrote works with 100, 200 records. But when it comes to 20000 of them there is a time out exception.
This is the stored procedure:
DECLARE #TEMP TABLE (Page_No varchar(MAX))
DECLARE #TEMP2 TABLE (Page_No varchar(MAX))
INSERT INTO #TEMP(Page_No)
SELECT
CAST(CC.query('data(PageId)') AS NVARCHAR(MAX)) AS Page_No
FROM
#XML.nodes('DocumentElement/CusipsFile') AS tt(CC)
INSERT INTO #TEMP2(Page_No)
SELECT Page_No
FROM tbl_Cusips_Pages
INSERT INTO tbl_Cusips_Pages(Page_No, Download_Status)
SELECT Page_No, 'False'
FROM #TEMP
WHERE Page_No NOT IN (SELECT Page_No FROM #TEMP
INTERSECT
SELECT Page_No FROM #TEMP2)
How can I solve this? Is there a better way to write this procedure?
As was already suggested, NVARCHAR(MAX) column/variable is very slow and has limited options. If you can change it, it would help a lot.
MERGE tbl_Cusips_Pages
USING (
SELECT
CAST(CC.query('data(PageId)') AS NVARCHAR(4000))
FROM
#XML.nodes('DocumentElement/CusipsFile') AS tt(CC)
) AS source (Page_No)
ON tbl_Cusips_Pages.Page_No = source.Page_No
WHEN NOT MATCHED BY TARGET
THEN INSERT (Page_No, Download_Status)
VALUES (source.Page_No, 'false')
Anyway, your query is not that bad either, just put the queries directly into the third one (TEMP2 one for sure) instead of inserting the data into the table variables. Table variables are quite slow in comparison.
Replace last INSERT Statement with following Script, I have replace IN Clause With NOT EXISTS that may help you for better performance.
DECLARE #CommanPageNo TABLE (Page_No varchar(MAX))
INSERT INTO #CommanPageNo SELECT Page_No FROM #TEMP
INTERSECT
SELECT Page_No FROM #TEMP2
INSERT INTO tbl_Cusips_Pages(Page_No, Download_Status)
SELECT Page_No, 'False'
FROM #TEMP
WHERE NOT EXISTS (SELECT 1 FROM #CommanPageNo WHERE Page_No=#CommanPageNo.Page_No)

select value into variable and alias in SQL Server

I'd like to simultaneously do two things in an MSSQL query:
select a field's value into a variable
select #myvar = colName from tableName
alias my column
select colName as [myCol] from tableName
I've tried these things:
Attempted Syntax select #myvar = colName as [myCol] from tableName
Attempted Syntax select #myvar = (colName as [myCol]) from tableName
Attempted Syntax select (#myvar = colName) as [myCol] from tableName
checked select statement syntax: https://msdn.microsoft.com/en-us/library/ms176104.aspx
If this is possible, how can it be accomplished?
A select can either assign values to variables or return column values, but not both.
In some cases, e.g. when using select to provide data to an insert, an output clause may be useful. A tool well worth having in your pocket as it provides access to identity values from insert and both before and after values when used with update.

Select values from SQL table - leave specific column names (name condition)

I have SQL table like this:
create table [Tbl](
[_Id] int Identity(1, 1),
[_ProjectId] int,
[Name] varchar(255),
[Age] int
...
Primary Key([_Id])
)
I need to select all values but not from the columns which names started by "_" (_Id, _ProjectId). How can I do it?
(For understanding: I have many tables like this with their specific columns. I don't know all the colum names).
You list the columns you want in the column list of your query. Don't add the columns that begins with a _.
Update:
You can build the query dynamically in for example a stored procedure where you have table name as a parameter. Use the sys.columns to get the column names and exclude the columns you don't want.
create procedure YourProcedure
#TableName sysname
as
declare #SQL nvarchar(max)
set #SQL = '
select '+stuff((select ','+quotename(name)
from sys.columns
where object_id = object_id(#TableName) and
left(name, 1) <> '_'
for xml path(''), type).value('text()[1]', 'sysname'),1,1,'')+'
from '+quotename(#TableName)
exec sp_executesql #SQL
SQL Fiddle
You can't use wildcards on column names.
Either select all with
select * from table
or specify which columns you want to select witt their full name
select name, age from table
List the columns you want separated by commas , instead of *
SELECT Name, Age, Col3, Col4, ColN FROM Tb1

Use SELECT result for another query

Is there any way other than using a cursor that I can use SELECT results for a subsequent INSERT/UPDATE query?
Something like:
DECLARE #SELECTRESULT;
SELECT Something into #SELECTRESULT
FROM Somewhere
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT Something, GETDATE(), 'XXX'
FROM #SELECTRESULT
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE
Something in
(SELECT Something FROM #SELECTRESULT)
The reason is that I have a relatively complex query from multiple tables and I don't want duplicate this code, once for the insert and second time for the update.
You can use a table variable.
Something like
DECLARE #Table TABLE(
Col1 INT
)
INSERT INTO #Table
SELECT Col1
FROM Table
Have a look at
Table Variables In T-SQL
DECLARE #local_variable (Transact-SQL)
Just use a temporary table it's ok for your case :
SELECT Something into #temporary_table FROM Somewhere WHERE blabla
use a temp table.
CREATE TABLE #tempTable
(
Something int NOT NULL,
CurrentDate DateTime NULL,
XXX Varchar(50)
)
Then use your complex query on multiple tables and insert the result set into the tempTable.
Insert into #tempTable
-- Complex Select Query
Just make sure that the columns returned by the selected query match in the order as per the #tempTable structure. Also the number of columns should match.
Once you have #tempTable with the complex data, you can use it multiple number of times for insert and update queries.
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT * from #tempTable
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE
Something in (SELECT Something FROM #tempTable)
DECLARE #SELECTRESULT table(Something nvarchar(50)) --the data that you could reuse.
insert into #SELECTRESULT(Something)
SELECT Something
FROM Somewhere
INSERT INTO SomewhereElse (X, XX, XXX)
SELECT Something, GETDATE(), 'XXX'
FROM #SELECTRESULT
UPDATE Somewhere
Set SomethingElse = 'ABC'
WHERE Something in
(SELECT Something FROM #SELECTRESULT)

Resources