Add values of a column of one table as columns to another table - sql

I am getting trouble in inserting values of a column from one table as columns in another table.
I am having Table A with some values in col1 :
And another Table B with columns equal to values of col1.
I want to add rest of the values from Table A, col1 as columns in Table B. Please help me out solving my problem. I am using SQL server 2012.

Create table tableA
(
Col1 varchar(50)
)
Create table tableB
(
Col1 varchar(50)
)
Insert into tableA values ('abc')
Insert into tableA values ('bbb')
Insert into tableA values ('ddd')
Insert into tableA values ('Col2')
Insert into tableA values ('Col3')
go
Declare #colName varchar(5000), #Text varchar(5000)
if EXISTS (select 1 from sys.tables where object_id=OBJECT_ID('tableB'))
BEGIN
SELECT #colName=ISNULL(#colName,'')+ (Col1) + ' varchar(50), ' FROM tableA WHERE Col1 not in (SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('tableB'))
select #colName= SUBSTRING (#colName,0,LEN(#colName))
select #colName
SET #Text='ALTER table tableB Add '+#colName
END
ELSE
BEGIN
print 1
SELECT #colName=ISNULL(#colName,'')+ (Col1) + ' varchar(50), ' FROM tableA
group by Col1
select #colName= SUBSTRING (#colName,0,LEN(#colName))
select #colName
SET #Text = 'CREATE TABLE tableB ( '+#colName+' )'
END
select #Text
EXEC (#Text)
select * from tableA
select * from tableB

Related

Compare Column names from 2 diff table in diff db in MS SQL

I am trying to get column names from 2 diff tables in diff db and compare them to see if there is any extra column in any table. They should match exactly. One possible solution could be getting all the column names from both table and dump in a temp table side by side and compare? Pls help.
IF OBJECT_ID('tempdb..#myTable') IS NOT NULL DROP TABLE #myTable
CREATE table #myTable (
table1 varchar(100) null,
table2 varchar(100) null
)
INSERT INTO #myTable (table1)
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('table1')
select * from #mytable
DROP TABLE #mytable
I modified your query to this
IF OBJECT_ID('tempdb..#myTable') IS NOT NULL DROP TABLE #myTable
CREATE table #myTable
(
rowNum int IDENTITY(1,1),
table1 varchar(100) null
)
GO
IF OBJECT_ID('tempdb..#myTable2') IS NOT NULL DROP TABLE #myTable2
CREATE table #myTable2
(
rowNum int IDENTITY(1,1),
table2 varchar(100) null
)
GO
USE database1 --your 1st database name here
GO
INSERT INTO #myTable (table1)
(
SELECT
name
FROM sys.columns
WHERE object_id = OBJECT_ID('Table_1'))
GO
USE database2 -- your 2nd database name here
GO
INSERT INTO #myTable2 (table2)
(
SELECT
name
FROM sys.columns
WHERE object_id = OBJECT_ID('Table_2'))
GO
SELECT table1,table2
FROM #myTable m
FULL OUTER JOIN #myTable2 m2 ON m.rowNum = m2.rowNum
ORDER BY table1,table2
DROP TABLE #mytable
DROP TABLE #mytable2

CHAR(4) did not show FOUR CHAR in Table Join

Okay the title cannot explain the situation correct enough.
Now this is it,
I have a table with columns
Table1
Columns0, CHAR(20), NOT NULL.
Columns1, CHAR(4), Allow Nulls.
Data : 'ARR '
Table2
Columns0, CHAR(20), NOT NULL.
Columns1, CHAR(4), NOT NULL.
Data : 'ARR '
Then I join two tables together.
SELECT (ISNULL(a.Columns1,'') + ISNULL(b.Columns1,'')) AS WhatEver
FROM Table1 a
left join Table2 b on a.Columns0 = b.Columns0
The result should appear as 'ARR ARR '
instead of this, it appear as 'ARRARR '
Why does this happen?
EDIT 2012/06/11:
After struggling, I ended up doing things like:
SELECT ISNULL(CONVERT(CHAR(4),a.Columns1),'') + ISNULL(b.Columns1,'')
Then only I get correct result 'ARR ARR '
But I am pretty sure my data type is CHAR(4) in the database.
Thank guys..
EDIT 2012/08/06:
Another solution that I found working is to change the TABLE 2 COLUMN 1 to (CHAR(4), NULL).
This can be done through
ALTER TABLE [table_name] MODIFY [column_name] [column_data_type] [null|not null]
Your example works fine on my server (SQL Server 2008 R2):
create table SOxx1
(
col1 char(4),
col2 char(20) not null
)
create table SOxx2
(
col1 char(4),
col2 char(20) not null
)
Go
insert into SOxx1 (col1, col2) VALUES ('ARR ', 'abc')
insert into SOxx2 (col1, col2) VALUES ('ARR ', 'abc')
go
SELECT (ISNULL(a.col1,'') + ISNULL(b.col1,'')) AS WhatEver
FROM SOxx1 a
left join SOxx2 b on a.Col2 = b.Col2
-- OUTPUT is 'ARR ARR '
Are you sure your columns are CHAR and not VARCHAR?
Nothing is stripping spaces after you get the result from SQL Server?
Can you try this:
declare #table1 table (id int, one char(4))
declare #table2 table (id int, one char(4))
insert into #table1 values (1 ,'ARR ')
insert into #table2 values (1 ,'ARR ')
select (isnull(a.one,'') + isnull(b.one,'')) AS WhatEver
from #table1 a left join #table2 b on a.id = b.id
I get, as expected,
ARR ARR
Have you tried different collations?
SELECT ISNULL(a.Columns1,'') collate Latin1_General_BIN + ISNULL(b.Columns1,'') collate Latin1_General_BIN AS WhatEver
FROM Table1 a
left join Table2 b on a.Columns0 = b.Columns0
SELECT (ISNULL(a.Columns1,'') +ISNULL(b.Columns1,'')) AS WhatEver FROM Table1 a left join Table2 b on a.Columns0 = b.Columns0

sql like clause multiple values

I have a table with multiple words, from 1 to n.
declare #words table
(
word varchar(100) not null
)
insert into #words (word) values ('word1')
insert into #words (word) values ('word2')
insert into #words (word) values ('word3')
declare #tablea table
(
column1 varchar(100) not null
)
insert into #tablea (column1) values ('aword1a aword2a aword3a')
insert into #tablea (column1) values ('word2a')
insert into #tablea (column1) values ('word3a')
Im having trouble to write a query to select from a table where a column is like these words, and I need the AND operator. If the table contains word1, word2, word3, the like clause must match the three words, it means, I want to return the first row in tablea.
select *
from tablea
where
column1 like ?
Updated:
select t.column1
from #tablea t
inner join #words w on charindex(w.word, t.column1) > 0
group by t.column1
having count(distinct w.word) = (select count(*) from #words)
Since any one column needs to contain all the values in the #words table, I would use a not exists, and try to find a value in #words that isn't contained in the column1 field.
select
*
from
#tablea a
where not exists (
select 1
from #words w
where a.column1 not like '%' + w.word + '%'
)
This will do it, but I'm not sure how extensible it is:
SELECT column1
FROM #tablea t
JOIN #words w ON t.column1 LIKE '%'+w.word+'%'
GROUP BY column1
HAVING COUNT(*) = (SELECT COUNT(*) FROM #words)
In the long run, you may be better off implementing Full Text Search.

Convert Rows Into Columns in SQL

Table A
ID COLA
-----------------------
A value1
B value1
C value1
Table B
ID DETAIL_ID COL_X COL_Y
A 0 foo foo
A 1 bar bar
B 0 foo foo
My expected out is something like
ID COLA COL_X_0 COL_X_1 COL_Y_0 COL_Y_1
A value1 foo bar foo bar
B value1 foo NULL foo NULL
C value1 NULL NULL NULL NULL
It means the rows of table B will be column values based on DETAIL_ID column.
I tried to write queries for this , but can't succeed due to following.
Number of DetailID values will NOT be fixed-length.It means I can't hard-coded the name of the columns.
This will give the exact output you described and you can add more columns if needed
DECLARE #a table (id char, cola varchar(10))
DECLARE #b table (id char, detail_id int, colx char(3), coly char(3))
INSERT #a values('A', 'value1'),('B', 'value2'),('C','value3')
INSERT #b values('A', 0, 'foo', 'foo'),('A', 1, 'bar', 'bar'),
('B',0, 'foo','foo')--,('A', 2, 'bar', 'bar') -- add this for extra columns
CREATE TABLE ##t(id char, detail_id tinyint, colvalue char(3), col varchar(8), cola varchar(10))
DECLARE #columns varchar(max)=''
DECLARE #sqlstring varchar(1000)
;WITH a as (
SELECT a.id, a.cola, b.detail_id, colx, coly,
'col_x_' + cast(detail_id as varchar) col_a,
'col_y_' + cast(detail_id as varchar) col_b
FROM #a a LEFT JOIN #b b on a.id = b.id
)
INSERT ##t
SELECT id, detail_id, colx, col_a, cola FROM a
UNION
SELECT id, detail_id, coly, col_b, cola FROM a
ORDER BY 4,2
SELECT #columns = coalesce(#columns, '') +',[' + col + ']'
FROM (
SELECT DISTINCT col, detail_id FROM ##t where not col is null
) a
SET #columns = stuff(#columns, 1,1,'')
SET #sqlstring =
'SELECT * FROM (
SELECT id, cola, col, colvalue FROM ##t
) b
PIVOT(max(colvalue) FOR col
in(
'+#columns+'))AS p order by 1'
EXEC(#sqlstring)
DROP TABLE ##t
SQL queries must specify the columns of the result set. That's fundamental to SQL. Even PIVOT requires that your query specify the columns before you send it to the RDBMS.
For that reason, it's difficult and error-prone to create a query that returns rows as columns as you describe, and can adapt as needed to any number of columns.
Handling dynamic columns must be a two-stage procedure.
One option is to make the two stages be:
Write application code to build the SQL query dynamically, based on the distinct values found in the data. This requires an extra query to discover what values exist so you can build the query.
Execute the SQL query and retrieve the results.
The other option is to make the two stages be:
Run a more plain SQL query, that fetches rows as rows, as they are stored in the database.
Write application code to post-process the results, collecting individual values from rows into an expanding set of columns based on the values found. This does not require an extra query as the first design does.
Just join table A and B on B.DETAIL_ID == A.ID ?? Or is that too simple?

SQL Server SELECT into existing table

I am trying to select some fields from one table and insert them into an existing table from a stored procedure. Here is what I am trying:
SELECT col1, col2
INTO dbo.TableTwo
FROM dbo.TableOne
WHERE col3 LIKE #search_key
I think SELECT ... INTO ... is for temporary tables which is why I get an error that dbo.TableTwo already exists.
How can I insert multiple rows from dbo.TableOne into dbo.TableTwo?
SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:
INSERT INTO dbo.TABLETWO
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE #search_key
This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:
INSERT INTO dbo.TABLETWO
(col1, col2)
SELECT col1, col2
FROM dbo.TABLEONE
WHERE col3 LIKE #search_key
There are two different ways to implement inserting data from one table to another table.
For Existing Table - INSERT INTO SELECT
This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.
----Create testable
CREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))
----INSERT INTO TestTable using SELECT
INSERT INTO TestTable (FirstName, LastName)
SELECT FirstName, LastName
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
For Non-Existing Table - SELECT INTO
This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.
----Create a new table and insert into table using SELECT INSERT
SELECT FirstName, LastName
INTO TestTable
FROM Person.Contact
WHERE EmailPromotion = 2
----Verify that Data in TestTable
SELECT FirstName, LastName
FROM TestTable
----Clean Up Database
DROP TABLE TestTable
Ref 1 2
It would work as given below :
insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""
If the destination table does exist but you don't want to specify column names:
DECLARE #COLUMN_LIST NVARCHAR(MAX);
DECLARE #SQL_INSERT NVARCHAR(MAX);
SET #COLUMN_LIST = (SELECT DISTINCT
SUBSTRING(
(
SELECT ', table1.' + SYSCOL1.name AS [text()]
FROM sys.columns SYSCOL1
WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
ORDER BY SYSCOL1.object_id
FOR XML PATH ('')
), 2, 1000)
FROM
sys.columns SYSCOL2
WHERE
SYSCOL2.object_id = object_id('dbo.TableOne') )
SET #SQL_INSERT = 'INSERT INTO dbo.TableTwo SELECT ' + #COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + #search_key
EXEC sp_executesql #SQL_INSERT
select *
into existing table database..existingtable
from database..othertables....
If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames
IF you want a identity column in new table created with select into then it can be done as below.
SELECT
ID = IDENTITY(INT, 1, 1),
name
INTO table2
FROM table1
If you want to insert into Table_A, from Table_B, only if the column is not in Table_A, then use the following:
BEGIN TRANSACTION
INSERT INTO dbo.Table_A (Column_1)
SELECT DISTINCT Some_Column AS Column_1
FROM dbo.Table_B
WHERE Some_Column
NOT IN (SELECT DISTINCT GroupId
FROM dbo.Table_A)
COMMIT