Temporary table in where clause - sql

I need some records from Temporary table and for this I am trying to run following query:
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies,#temp_table
Where Companies.ID = #temp_table.Id
But in Where clause I am getting this error:
The scalar variable #temp_table must be declared.

The correct code should be like :
DECLARE #temp_table TABLE (Id uniqueidentifier, Dates nvarchar(10))
INSERT #temp_table
SELECT ID,Right(Companies.UserDefined4, 10)
FROM Companies
Select *
From Companies c
join #temp_table t
on c.ID = t.Id

Try
SELECT *
FROM Companies c
INNER JOIN #temp_table t ON c.ID = t.ID

Related

How to capture columns from joined tables using output clause?

I am updating a table called tableA by joining tableB and tableC at the same time I am capturing updated records into temp table using output clause from tableA . Now I want capture columns from table B for the updated data but output clause isn't allowing the same.
Eg:
Update SLC Set SLC.Datascrublevel = C.Datascrublevel
OUTPUT [Deleted].Systemcode,
[Deleted].Systemkey,
[Deleted].datascrublevel,
[Inserted].datascrublevel
INTO #TEMP1
FROM TABLEA SLC with(nolock)
INNER JOIN TABLEB SC ON SC.SystemCode = SLC.SystemCode
INNER JOIN TABLEC SL ON SL.SystemCode = SLC.SystemCode and SLC.SystemKey = SL.Systemkey
INNER JOIN #TEMP C ON SLC.Datascrublevel <> C.DataScrubLevel AND C.Systemcode = SLC.SystemCode and C.Systemkey = SLC.SystemKey
Now I want columns from tableB to capture into temp table using output clause. Please provide your advise if there are any alternative ways.
Just Like you have given it as [deleted].[Column Name] and [Inserted].[Column Name] add one more column as [SC].[Column Name]
Example :
IF OBJECT_ID('TempDb..#TABLEA') IS NOT NULL
DROP TABLE #TABLEA
IF OBJECT_ID('TempDb..#TABLEB') IS NOT NULL
DROP TABLE #TABLEB
IF OBJECT_ID('TempDb..#TABLEC') IS NOT NULL
DROP TABLE #TABLEC
IF OBJECT_ID('TempDb..#TABLED') IS NOT NULL
DROP TABLE #TABLED
CREATE TABLE #TABLEA
(
SeqNo INT IDENTITY(1,1),
MyDate DATE
)
CREATE TABLE #TABLEB
(
SeqNo INT IDENTITY(1,1),
FullName VARCHAR(20)
)
CREATE TABLE #TABLEC
(
SeqNo INT IDENTITY(1,1),
FullName VARCHAR(20),
MyDate DATE
)
CREATE TABLE #TABLED
(
SeqNo INT,
MyDate DATE,
FullName VARCHAR(20)
)
INSERT INTO #TABLEA
(
MyDate
)
SELECT GETDATE()
UNION
SELECT GETDATE()+1
UNION
SELECT GETDATE()-1
INSERT INTO #TABLEB
(
FullName
)
VALUES('A'),('B'),('C')
INSERT INTO #TABLEC
(
FullName
)
VALUES('A'),('B'),('C')
UPDATE C
SET MyDate = A.MyDate
OUTPUT
deleted.SeqNo,
deleted.MyDate,
B.FullName
INTO #TABLED
FROM #TABLEC C
INNER JOIN #TABLEB B
ON C.FullName = B.FullName
INNER JOIN #TABLEA A
ON A.SeqNo = B.SeqNo
SELECT * FROM #TABLED

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

Getting time out exception when run this query from vs

this are the my table structure i need each category subcategory's count and question count of the related category where Isparent=1 from category table this is my result table
This is my code
My prob is it run in sql server while running from application(VS) it throw a time our error
where i did mistake help me out frnds.
thanks in advance.
DECLARE #TEMP TABLE (CategoryID INT,NAME VARCHAR(52))
INSERT INTO #TEMP SELECT CategoryID,Name FROM EC_M_CategoriesMaster where IsParent=1
DECLARE #TEMP1 TABLE ( CategoryID INT,cCOUNTS INT)
INSERT INTO #TEMP1 SELECT te.CategoryID,COUNT((ISNULL(te1.PCategoryID,0)))
AS Ccount from #TEMP te inner join EC_M_CategoriesMaster te1 on te.CategoryID=te1.PCategoryID GROUP BY te.CategoryID
DECLARE #TEMP2 TABLE (CategoryID INT,COUNTS INT )
INSERT INTO #TEMP2 SELECT CategoryID,COUNT((ISNULL(QuestionID,0)))
AS Qcount from EC_M_QuestionMaster GROUP BY CategoryID
SELECT t1.CategoryID,t1.Name,ISNULL(t.COUNTS,0) as Qcount,ISNULL(MY.cCOUNTS,0) AS CatCount from
#TEMP2 t RIGHT OUTER JOIN
#TEMP t1 ON t.CategoryID=t1.CategoryID
LEFT JOIN #TEMP1 MY ON MY.CategoryID=T1.CategoryID

Query to update records from two different tables

I have a query that updates table records.
UPDATE #TEMP
SET [fld_LastName] = CustomerProfile.fld_LastName
,fld_FirstName = CustomerProfile.fld_FirstName
,fld_BirthDate = CustomerProfile.fld_BirthDate
FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile --c
WHERE CustomerProfile.fld_CustomerNo = #TEMP.fld_CustomerNo
I want to update the records when the customer is not present in:
[DB_1].[dbo].[tbl_Customer]
I would want to look up to:
[DB_2].[dbo].[tbl_Customer]
How can i do that in an SQL Query?
Thanks a lot.
This should work for you:
UPDATE B
SET [fld_LastName] = CustomerProfile.fld_LastName
,fld_FirstName = CustomerProfile.fld_FirstName
,fld_BirthDate = CustomerProfile.fld_BirthDate
FROM [DB_1].[dbo].[tbl_Customer] AS CustomerProfile INNER JOIN #TEMP B
ON CustomerProfile.fld_CustomerNo = B.fld_CustomerNo
WHERE B.[fld_LastName] IS NULL OR B.fld_FirstName IS NULL OR B.fld_BirthDate IS NULL
You can do it with one update. Something like this:
DECLARE #a TABLE (id INT, val INT)
DECLARE #b TABLE (id INT, val INT)
DECLARE #c TABLE (id INT, val INT)
INSERT #a SELECT 1,NULL UNION SELECT 2,NULL UNION SELECT 3,30
INSERT #b SELECT 1,10
INSERT #c SELECT 1,20 UNION SELECT 2,20
SELECT * FROM #a
UPDATE #a
SET val = COALESCE(b.val,c.val,a.val)
FROM #a a
LEFT JOIN
#b b ON a.id=b.id
LEFT JOIN
#c c ON a.id=c.id
SELECT * FROM #a
This assumes that you prefer NOT NULL values from DB_2 to NULL values in DB_1--if those fields are even nullable.
UPDATE #TEMP
SET fld_LastName = COALESCE(b.fld_LastName,c.fld_LastName,a.fld_LastName)
,fld_FirstName = COALESCE(b.fld_FirstName,c.fld_FirstName,a.fld_FirstName)
,fld_BirthDate = COALESCE(b.fld_BirthDate,c.fld_BirthDate,a.fld_BirthDate)
FROM #Temp a
LEFT JOIN
DB_1.dbo.tbl_Customer b ON a.fld_CustomerNo = b.fld_CustomerNo
LEFT JOIN
DB_2.dbo.tbl_Customer c ON a.fld_CustomerNo = c.fld_CustomerNo

Delete duplicated rows and Update references

How do I Delete duplicated rows in one Table and update References in another table to the remaining row? The duplication only occurs in the name. The Id Columns are Identity columns.
Example:
Assume we have two tables Doubles and Data.
Doubles table (
Id int,
Name varchar(50)
)
Data Table (
Id int,
DoublesId int
)
Now I Have Two entries in the Doubls table:
Id Name
1 Foo
2 Foo
And two entries in the Data Table:
ID DoublesId
1 1
2 2
At the end there should be only one entry in the Doubles Table:
Id Name
1 Foo
And two entries in the Data Table:
Id DoublesId
1 1
2 1
In the doubles Table there can be any number of duplicated rows per name (up to 30) and also regular 'single' rows.
I've not run this, but hopefully it should be correct, and close enough to the final soln to get you there. Let me know any mistakes if you like and I'll update the answer.
--updates the data table to the min ids for each name
update Data
set id = final_id
from
Data
join
Doubles
on Doubles.id = Data.id
join
(
select
name
min(id) as final_id
from Doubles
group by name
) min_ids
on min_ids.name = Doubles.name
--deletes redundant ids from the Doubles table
delete
from Doubles
where id not in
(
select
min(id) as final_id
from Doubles
group by name
)
Note: I have taken the liberty to rename your Id's to DoubleID and DataID respectively. I find that eassier to work with.
DECLARE #Doubles TABLE (DoubleID INT, Name VARCHAR(50))
DECLARE #Data TABLE (DataID INT, DoubleID INT)
INSERT INTO #Doubles VALUES (1, 'Foo')
INSERT INTO #Doubles VALUES (2, 'Foo')
INSERT INTO #Doubles VALUES (3, 'Bar')
INSERT INTO #Doubles VALUES (4, 'Bar')
INSERT INTO #Data VALUES (1, 1)
INSERT INTO #Data VALUES (1, 2)
INSERT INTO #Data VALUES (1, 3)
INSERT INTO #Data VALUES (1, 4)
SELECT * FROM #Doubles
SELECT * FROM #Data
UPDATE #Data
SET DoubleID = MinDoubleID
FROM #Data dt
INNER JOIN #Doubles db ON db.DoubleID = dt.DoubleID
INNER JOIN (
SELECT db.Name, MinDoubleID = MIN(db.DoubleID)
FROM #Doubles db
GROUP BY db.Name
) dbmin ON dbmin.Name = db.Name
/* Kudos to quassnoi */
;WITH q AS (
SELECT Name, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Name) AS rn
FROM #Doubles
)
DELETE
FROM q
WHERE rn > 1
SELECT * FROM #Doubles
SELECT * FROM #Data
Take a look at this one, i have tried this, working fine
--create table Doubles ( Id int, Name varchar(50))
--create table Data( Id int, DoublesId int)
--select * from doubles
--select * from data
Declare #NonDuplicateID int
Declare #NonDuplicateName varchar(max)
DECLARE #sqlQuery nvarchar(max)
DECLARE DeleteDuplicate CURSOR FOR
SELECT Max(id),name AS SingleID FROM Doubles
GROUP BY [NAME]
OPEN DeleteDuplicate
FETCH NEXT FROM DeleteDuplicate INTO #NonDuplicateID, #NonDuplicateName
--Fetch next record
WHILE ##FETCH_STATUS = 0
BEGIN
--select b.ID , b.DoublesID, a.[name],a.id asdasd
--from doubles a inner join data b
--on
--a.ID=b.DoublesID
--where b.DoublesID<>#NonDuplicateID
--and a.[name]=#NonDuplicateName
print '---------------------------------------------';
select
#sqlQuery =
'update b
set b.DoublesID=' + cast(#NonDuplicateID as varchar(50)) + '
from
doubles a
inner join
data b
on
a.ID=b.DoublesID
where b.DoublesID<>' + cast(#NonDuplicateID as varchar(50)) +
' and a.[name]=''' + cast(#NonDuplicateName as varchar(max)) +'''';
print #sqlQuery
exec sp_executeSQL #sqlQuery
print '---------------------------------------------';
-- now move the cursor
FETCH NEXT FROM DeleteDuplicate INTO #NonDuplicateID ,#NonDuplicateName
END
CLOSE DeleteDuplicate --Close cursor
DEALLOCATE DeleteDuplicate --Deallocate cursor
---- Delete duplicate rows from original table
DELETE
FROM doubles
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM doubles
GROUP BY [NAME]
)
Please try and let me know if this helped you
Thanks
~ Aamod
If you are using MYSQL following worked for me. I did it for 2 steps
Step 1 -> Update all Data rows to one Double table reference (with lowest id)
Step 2 -> Delete all duplicates with keeping lowest id
Step 1 ->
update Data
join
Doubles
on Data.DoublesId = Doubles.id
join
(
select name, min(id) as final_id
from Doubles
group by name
) min_ids
on min_ids.name = Doubles.name
set DoublesId = min_ids.final_id;
Step 2 ->
DELETE c1 FROM Doubles c1
INNER JOIN Doubles c2
WHERE
c1.id > c2.id AND
c1.name = c2.name;