"Invalid Column" when using column from table variable - sql

I'm trying to declare a table variable and then join it to a table I created in the database. Every time I try to insert my "NAME" field into my table, I get the error 'Invalid Column Name "NAME"', even though the GNAME field works fine. What am I doing wrong, and how can I join me NAME column?
DECLARE #Names TABLE
(
ID INT,
NAME VARCHAR(100),
GNAME VARCHAR(100)
)
INSERT INTO #Names
(
ID,
NAME,
GNAME
)
SELECT
CName.ID,
Ref.NAME,
Ref.GNAME
FROM
#CurrentPositions AS CName
LEFT OUTER JOIN
dbo.NameField AS Ref
ON
CName.ID = Ref.ID
IF ( OBJECT_ID('dbo.ReportTable', 'U') IS NOT NULL)
DROP TABLE dbo.ReportTable
CREATE TABLE [dbo].[ReportTable]
(
[ID_NUMBER] [INT],
[NAME] [VARCHAR](150)
[GNAME] [VARCHAR](150)
)
INSERT INTO [dbo].[ReportTable]
(
ID_NUMBER,
NAME,
GNAME
)
SELECT
C.ID_NUMBER,
N.NAME,
N.GNAME
FROM
#Names AS N
INNER JOIN
#CurrentPositions AS C
ON N.ID_NUMBER = C.ID_NUMBER

Try using a Temp table :
CREATE TABLE #Names
(
ID INT,
NAME VARCHAR(100),
GNAME VARCHAR(100)
)
INSERT INTO #Names
(
ID,
NAME,
GNAME
)
SELECT
CName.ID,
Ref.NAME,
Ref.GNAME
FROM
#CurrentPositions AS CName
LEFT OUTER JOIN
dbo.NameField AS Ref
ON
CName.ID = Ref.ID
IF ( OBJECT_ID('dbo.ReportTable', 'U') IS NOT NULL)
DROP TABLE dbo.ReportTable
CREATE TABLE [dbo].[ReportTable]
(
[ID_NUMBER] [INT],
[NAME] [VARCHAR](150)
[GNAME] [VARCHAR](150)
)
INSERT INTO [dbo].[ReportTable]
(
ID_NUMBER,
NAME,
GNAME
)
SELECT
C.ID_NUMBER,
N.NAME,
N.GNAME
FROM
#Names AS N
INNER JOIN
#CurrentPositions AS C
ON N.ID_NUMBER = C.ID_NUMBER
I've assumed that you will also change the table variable #CurrentPositions to a temp table
Just remember to drop the tables after you use them.

It is quite possible that all you need to do is wrap your field names in square brackets, e.g.
INSERT INTO #Names
(
[ID],
[NAME],
[GNAME]
)
SELECT
CName.[ID],
Ref.[NAME],
Ref.[GNAME]
FROM
#CurrentPositions AS CName
LEFT OUTER JOIN
dbo.NameField AS Ref
ON
CName.[ID] = Ref.[ID]
If that doesn't fix it, please post the schema of your #CurrentPositions and dbo.NameField tables.

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

Delete only those records from Master when 'sku' and 'link' match with the child table

I want to delete only those records from Master when sku and link match with the child table
DECLARE #MASTER TABLE
(
SKU VARCHAR (50),
LINK VARCHAR (100)
)
INSERT #MASTER
SELECT 'A7061B', 'IMG_A7061S_A7061B.jpg' UNION ALL
SELECT 'A7063B', 'IMG_A7063S_A7063B.jpg' UNION ALL
SELECT 'A7065B', 'IMG_A7065S_A7065B.jpg'
SELECT * FROM #MASTER
DECLARE #CHILD TABLE
(
SKU VARCHAR (50),
LINK VARCHAR (100)
)
INSERT #CHILD
SELECT 'A7061B', 'IMG_A7061S_A7061B.jpg' UNION ALL
SELECT 'A7063B', 'IMG_A7063S_A7063B.jpg'
SELECT * FROM #CHILD
Expected Output
only below records should be deleted.
SKU, LINK
A7061B, IMG_A7061S_A7061B.jpg
A7063B, IMG_A7063S_A7063B.jpg
In SQL Server you need a query like the following:
DELETE m
FROM #MASTER AS m
INNER JOIN #CHILD AS c ON m.LINK = c.LINK AND m.SKU = c.SKU

How can I pull data from multiple sql tables using a join statement

I'm designing a simple in-office ticket system, and would like to include a field for the party responsible for the next action. To do so right this moment I'm thinking of using tableName and tableID as specifiers for the specific responsible party (could be a technician, customer, or third party, all in different tables)
It would be fine to pull that data in and run another select call using the name of the table as a parameter, but the extra data flow slows things down significantly.
Is there a way to use a single join statement to return the details of the party with a column for the table name and one for the individual table id or is there a better way to store the data from multiple potential tables?
You can use left join to achieve your requirement :-
Set Nocount On;
Declare #OfficeTickets Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,PartyType Varchar(1)
,TechnicianId Int Null
,CustomerId Int Null
,ThirdPartyId Int Null
)
Declare #OfficeTickets1 Table
(
Id Int Identity(1,1)
,Column1 Varchar(100)
,TableName Varchar(100)
,TableId Int Null
)
Declare #Technician Table
(
Id Int Identity(1,1)
,TechnicianName Varchar(100)
)
Declare #Customers Table
(
Id Int Identity(1,1)
,CustomerName Varchar(100)
)
Declare #ThirdParty Table
(
Id Int Identity(1,1)
,ThirdPartyName Varchar(100)
)
Insert Into #Technician(TechnicianName) Values
('Technician_1')
,('Technician_2')
,('Technician_3')
Insert Into #Customers(CustomerName) Values
('Customer_1')
,('Customer_2')
,('Customer_3')
Insert Into #ThirdParty(ThirdPartyName) Values
('ThirdParty_1')
,('ThirdParty_2')
,('ThirdParty_3')
,('ThirdParty_4')
Insert Into #OfficeTickets(Column1,PartyType,TechnicianId,CustomerId,ThirdPartyId) Values
('ABC','T',3,Null,Null)
,('XYZ','C',Null,2,Null)
,('PUQ','P',Null,Null,4)
Insert Into #OfficeTickets1(Column1,TableName,TableId) Values
('ABC','Technician',3)
,('XYZ','Customers',2)
,('PUQ','ThirdParty',4)
---- taken separate columns for parties
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets As ot
Left Join #Technician As t On ot.PartyType = 'T' And ot.TechnicianId = t.Id
Left Join #Customers As c On ot.PartyType = 'C' And ot.CustomerId = c.Id
Left Join #ThirdParty As tp On ot.PartyType = 'P' And ot.ThirdPartyId = tp.Id
---- by TableName and TableId
Select ot.Id
,ot.Column1
,t.TechnicianName
,c.CustomerName
,tp.ThirdPartyName
From #OfficeTickets1 As ot
Left Join #Technician As t On ot.TableName = 'Technician' And ot.TableId = t.Id
Left Join #Customers As c On ot.TableName = 'Customers' And ot.TableId = c.Id
Left Join #ThirdParty As tp On ot.TableName = 'ThirdParty' And ot.TableId = tp.Id
output:-

Showing data as a column name

I have three tables. I called them as Table A,Table B,Table C.
And I have desired view which I want to get.
Table A
Aid RegNum BID Value
2CE7D0A7 2000000 D5981DFC OFFCRO
9D3C13AA 2000000 C58566C5 YCH - from
9DDB90C4 2000000 812E9E75 Y
Table B is connected to Table A by Table B's foreign key in Table A
Table B
BID Label ColumnName Order
D5981DFC Offered/Change Role StatusChangeCode 0
C58566C5 Offered/Role Change Comments StatusChangeComments 1
812E9E75 Assessed StatusChangeAssessed 2
Table C has foreign key in Table A as well. Reg Num. Reg num is primary key in Table C
Table C
Name Surname RegNum
Etibar Hasanov 2000000
As you see there are column's names which are datas in Table B
DesiredView
Name Surname RegNum StatusChangeCode StatusChangeComments StatusChangeAssessed
Etibar Hasanov 2000000 OFFCRO YCH - from Y
You can achieve this by using PIVOT table. Try something like this,
Create Table TableA(Aid varchar(50), RegNum int, BID Varchar(20), Value varchar(50))
insert into TableA values
('2CE7D0A7', 2000000, 'D5981DFC', 'OFFCRO'),
('9D3C13AA', 2000000, 'C58566C5', 'YCH - from' ),
('9DDB90C4', 2000000, '812E9E75', 'Y')
create Table TableB(BID Varchar(20), Label Varchar(50), ColumnName
Varchar(50), [Order] int)
insert into TableB values
('D5981DFC', 'Offered/Change Role', 'StatusChangeCode', 0),
('C58566C5', 'Offered/Role Change Comments', 'StatusChangeComments', 1),
('812E9E75', 'Assessed', 'StatusChangeAssessed', 2)
Create Table TableC (Name Varchar(20), Surname Varchar(20), RegNum int)
insert into TableC values
('Etibar', 'Hasanov', 2000000)
SELECT *
FROM (
SELECT
Name, SurName, C.RegNum, Value, B.ColumnName
FROM TableC C
JOIN TableA A ON C.RegNum = A.RegNum
JOIN TableB B on B.BID = A.BID
) AS Source
PIVOT
(
MAX(Value)
FOR [ColumnName]
in ( [StatusChangeCode], [StatusChangeComments], [StatusChangeAssessed] )
)AS Pvot
Sql Fiddle Demo
If you are using SQL server 2005, according to Microsoft Technet,
When PIVOT and UNPIVOT are used against databases that are upgraded to
SQL Server 2005 or later, the compatibility level of the database must
be set to 90 or higher.
I first selected columns names. In this table it brings [StatusChangeAssessed],[StatusChangeCode],[StatusChangeComments] . Then in the next query I setted #col ( column names ).
declare #nregnumber nvarchar(10)='2000000';
DECLARE #cols AS NVARCHAR(MAX), #runningquery as nvarchar(max);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(rn)
from
(
select columnname rn from tableb where exists ( select * from tablea where tablea.bid=tableb.bid and regnum=#nregnumber)
) t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
set #runningquery='
SELECT *
FROM (
SELECT
Name, SurName, C.RegNum, Value, B.ColumnName
FROM TableC C
JOIN TableA A ON C.RegNum = A.RegNum
JOIN TableB B on B.BID = A.BID
) AS Source
PIVOT
(
MAX(Value)
FOR [ColumnName]
in ( '+#cols+')
)AS Pvot'
exec (#runningquery)
Special thanks to Selva.

Find and insert dummy rows - possible scenario for OUTER APPLY

This is a mock up of the situation we've got:
IF OBJECT_ID('TEMPDB..#People') IS NOT NULL BEGIN DROP TABLE #People END;
CREATE TABLE #People
(
Name VARCHAR(100),
Category VARCHAR(20),
ID INT
);
INSERT INTO #People
values
('x','Bronze',1),
('y','Bronze',2),
('z','Silver',3),
('j','Gold',4),
('q','Bronze',5),
('x','Silver',1);
IF OBJECT_ID('TEMPDB..#Category') IS NOT NULL BEGIN DROP TABLE #Category END;
CREATE TABLE #Category
(
Category VARCHAR(100)
);
INSERT INTO #Category
values
('Gold'),
('Silver'),
('Bronze');
If a name does not have a Category e.g. x does not have Gold then I'd like a row creating and adding into the table #People with an ID of -1.
Current solution I have is this:
WITH x AS
(
SELECT DISTINCT
x.Name,
s.Category
FROM #People x
CROSS JOIN #Category s
)
INSERT INTO #People
SELECT J.Name,
J.Category,
ID = -1
FROM x J
WHERE NOT EXISTS
(
SELECT 1
FROM #People Q
WHERE J.Name = Q.Name
AND J.Category = Q.Category
);
See it works!...:
SELECT *
FROM #People;
I have a feeling CROSS APPLY might be a good operator to use in order to simplify the above - What is the simplest way to find, create and insert these rows?
insert into People(Name, Category, Id)
(
select distinct
p.Name,
c.Category,
p.Id
from
people p
cross join category c
where
Concat(p.id, c.Category) not in (select Concat(id, Category) from people)
);
http://www.sqlfiddle.com/#!6/92cd5/14