Receiving SQL Object Already named 'x' in the DB, Even after dropping - sql

IF OBJECT_ID('#TempTableHoldingRepairsList') IS NOT NULL
DROP TABLE #TempTableHoldingRepairsList
GO
SELECT
a.EnteredDate,
bb.EmployeeId,
bb.EmployeeName,
dd.EquipmentId,
dd.EquipmentName,
ee.PK_WorkOrder,
StatusName = 'NOT-SERVICEABLE'
INTO #TempTableHoldingRepairsList
FROM dbo.PIT_Inspection a
INNER JOIN dbo.PIT_EmployeeName bb
ON a.FK_EmployeeName = bb.PK_EmployeeName
INNER JOIN dbo.PIT_EquipmentName dd
ON a.FK_EquipmentName = dd.PK_EquipmentName
LEFT JOIN dbo.PIT_WorkOrder ee
ON ee.FK_EmployeeName = bb.PK_EmployeeName
WHERE a.FK_Status = 2
GROUP BY ee.PK_WorkOrder, a.EnteredDate, bb.EmployeeId, bb.EmployeeName, dd.EquipmentId, dd.EquipmentName
GO
--Now Count how many work orders for each.
SELECT COUNT(*) AS WorkOrderCount FROM PIT_WorkOrder pw
INNER JOIN #TempTableHoldingRepairsList th
ON th.PK_WorkOrder = pw.PK_WorkOrder
Not sure if I'm doing the final inner join wrong or missing something completely, but I continue to receive:
There is already an object named '#TempTableHoldingRepairsList' in the database.

You can't check for the existence of a temporary table directly they way you're doing it. You need to look in tempdb. You need to change the check to the following:
IF OBJECT_ID('tempdb..#TempTableHoldingRepairsList') IS NOT NULL
DROP TABLE #TempTableHoldingRepairsList
GO

Related

take dynamic table name for inner join in SQL Query

My SQL Query is,
SELECT EAL_TYPE,
EAL_ID,
ROW_NUMBER ()OVER(PARTITION BY EAL_TYPE,EAL_ID ORDER BY EAL_TYPE,EAL_ID,EAL_ACTION_TIME Desc)SL#,
EAL_STATUS,
EAL_ACTION_TYPE,
EAL_CMPCODE,
ESSET_Description,
EAL_SHOW_IN_ALERT,
ESSETRS_WEIGHTAGE,
Usr_UserRole,ESSET_HeaderTable_Prefix,ESSET_HeaderTable
FROM ESS_ACTION_LOG
LEFT JOIN ESS_ENTRYTYPE_MASTER ON
ESSET_ID=EAL_TYPE
LEFT JOIN User_Profile ON
Usr_LoginID='MK'
LEFT JOIN ESS_ENTRYTYPE_ROLE_SETTINGS ON
ESSETRS_CMPCODE = EAL_CMPCODE AND
ESSETRS_ID = EAL_TYPE AND
ESSETRS_ROLE_ID = Usr_UserRole
INNER JOIN ESSET_HeaderTable ON
ESSET_HeaderTable_Prefix+'_CMPCode'=EAL_CMPCODE AND
ESSET_HeaderTable_Prefix+'_Type'=EAL_TYPE AND
ESSET_HeaderTable_Prefix+'_ID'=EAL_ID
WHERE ESSETRS_WEIGHTAGE IS NOT NULL
In the above query, while executing it shows an error like 'ESSET_HeaderTable object name not found'. But that table name needs to come dynamically from another table. What's wrong with my query. Can anyone help me with this?

Code Explanation - Please

Sorry - I hope you don't mind me asking this question but I am new to SQL - Could someone comments on what these lines mean in this code:
select b.recipeuuid
,b.proditemuuid
,b.proditemvalueuuid
into #rectemp
from rec_recipe as a
inner join rec_recipevalue as b
on b.recipeuuid=a.recipeuuid
and b.[value] in ('Green','Yellow')
inner join rec_proditem as c
on c.proditemuuid=b.proditemuuid
inner join rec_proditemvalue as d
on d.proditemuuid=c.proditemuuid
and d.proditemvalueuuid=b.proditemvalueuuid
and d.[name]='SetupType'
;
update a
set a.[value]='1'
from rec_recipevalue as a
inner join #rectemp as b
on b.recipeuuid=a.recipeuuid
and b.proditemuuid=a.proditemuuid
and b.proditemvalueuuid=a.proditemvalueuuid
where a.[value] in ('Green','Yellow')
;
update a
set a.[name]='Normal'
from rec_proditemvalue as a
inner join #rectemp as b
on b.proditemuuid=a.proditemuuid
and b.proditemvalueuuid=a.proditemvalueuuid
where a.[name]='SetupType'
;
drop table #rectemp;
I understand that the general idea of this code. It is about how to update (or change) the value for two different columns: Attribute & Color. These two items are located in two different tables before I joined them with the appropriate UUID.
The update should take a place only when the Attribute = ‘SetupType’ and the Color = ‘Green’ or ‘Yellow’
I would like to change these two values to:
Attribute = ‘Normal’ and the
Color = ‘1’
select b.recipeuuid
,b.proditemuuid
,b.proditemvalueuuid
into #rectemp
from rec_recipe as a
inner join rec_recipevalue as b
on b.recipeuuid=a.recipeuuid
and b.[value] in ('Green','Yellow')
inner join rec_proditem as c
on c.proditemuuid=b.proditemuuid
inner join rec_proditemvalue as d
on d.proditemuuid=c.proditemuuid
and d.proditemvalueuuid=b.proditemvalueuuid
and d.[name]='SetupType'
;
***#rectemp is a temp table. Data imported into the table***
update a
set a.[value]='1'
from rec_recipevalue as a
inner join #rectemp as b
on b.recipeuuid=a.recipeuuid
and b.proditemuuid=a.proditemuuid
and b.proditemvalueuuid=a.proditemvalueuuid
where a.[value] in ('Green','Yellow')
;
***Column Value is updated to 1 based on Value is Green or yellow***
update a
set a.[name]='Normal'
from rec_proditemvalue as a
inner join #rectemp as b
on b.proditemuuid=a.proditemuuid
and b.proditemvalueuuid=a.proditemvalueuuid
where a.[name]='SetupType'
;
*** Name column is updated to Normal ***
drop table #rectemp;
*** Temp Table is dropped***

SQL View statement with 2 INNER JOINS

Can anyone help me with this issue I tried many times but still haven't found the solution
Here is the original View that I have in my database but now I made changes in the database and the view need to be changed also.
Here is the view as it was:
SELECT
[tableN].*,
[tabB].[att1] AS tabB_email, [tabB].[name] AS tabB_name,
[tabC].[name] AS tabC_name
FROM
[tabC]
INNER JOIN
([tableN]
INNER JOIN [tabB] ON [tableN].[sender_id] = [tabB].[ID])
ON [tabC].[ID] = [tableN].[recipient_id]
Here is what is the difficult point for me. Now I don't have this 2 tables tabB and tabC
They are now in one table tabX and have an identifier field roleId. I manage to get all the columns except the last one [tabC].[name] AS tabC_name
Any ideas?
Try like this
SELECT [tableN].*, [tabX].[att1] AS tabB_email, [tabX].[name] AS tabB_name,
t1.[name] AS tabC_name
FROM [tabX] as t INNER JOIN ([tableN] INNER JOIN [tabX]
ON [tableN].[sender_id] = [tabX].[roleid])
ON t.[roleid] = [tableN].[recipient_id]
SELECT [tableN].*, [Tabx] .[att1] AS tabB_email, [Tabx] .[name] AS tabB_name
FROM [Tabx] A
INNER JOIN [TABLEN] B
ON A.ROLEID=B.RECIPIENT_ID
SELECT [TableN].*, Bd.[email] AS bd_email, Bd.[showname] AS bd_name,
Pc.[showname] AS pc_name
FROM
[TABLE_X] AS Pc
INNER JOIN ([TableN]
INNER JOIN [TABLE_X] AS Bd
ON [TableN].[sender_id] = Bd.[ID] AND Bd.roleID = 1)
ON Pc.[ID] = [TableN].[recipient_id] AND Pc.roleID = 2
I finally find the the code that is working as needed

SQL query join conditions

I have a query (exert from a stored procedure) that looks something like this:
SELECT S.name
INTO #TempA
from tbl_Student S
INNER JOIN tbl_StudentHSHistory TSHSH on TSHSH.STUD_PK=S.STUD_PK
INNER JOIN tbl_CODETAILS C
on C.CODE_DETL_PK=S.GID
WHERE TSHSH.Begin_date < #BegDate
Here is the issue, the 2nd inner join and corresponding where statement should only happen if only a certain variable (#UseArchive) is true, I don't want it to happen if it is false. Also, in TSHSH certain rows might have no corresponding entries in S. I tried splitting it into 2 separate queries based on #UseArchive but studio refuses to compile that because of the INTO #TempA statement saying that there is already an object named #TempA in the database. Can anyone tell me of a way to fix the query or a way to split the queries with the INTO #TempA statement?
Looks like you're asking 2 questions here.
1- How to fix the SELECT INTO issue:
SELECT INTO only works if the target table does not exist. You need to use INSERT INTO...SELECT if the table already exists.
2- Conditional JOIN:
You'll need to do a LEFT JOIN if the corresponding row may not exist. Try this.
SELECT S.name
FROM tbl_Student S
INNER JOIN tbl_StudentHSHistory TSHSH
ON TSHSH.STUD_PK=S.STUD_PK
LEFT JOIN tbl_CODETAILS C
ON C.CODE_DETL_PK=S.GID
WHERE TSHSH.Begin_date < #BegDate
AND CASE WHEN #UseArchive = 1 THEN c.CODE_DETL_PK ELSE 0 END =
CASE WHEN #UseArchive = 1 THEN S.GID ELSE 0 END
Putting the CASE statement in the WHERE clause and not the JOIN clause will force it to act like an INNER JOIN when #UseArchive and a LEFT JOIN when not.
I'd replace it with LEFT JOIN
LEFT JOIN tbl_CODETAILS C ON #UseArchive = 1 AND C.CODE_DETL_PK=S.GID
You can split the queries and then insert into a temp table easily.
SELECT * INTO #TempA FROM
(
SELECT * FROM Q1
UNION ALL
SELECT * FROM Q2
) T
SELECT S.name
INTO #TempA
from tbl_Student S
INNER JOIN tbl_StudentHSHistory TSHSH
on TSHSH.STUD_PK = S.STUD_PK
INNER JOIN tbl_CODETAILS C
on C.CODE_DETL_PK = S.GID
and #UseArchive = true
WHERE TSHSH.Begin_date < #BegDate
But putting #UseArchive = true in the join in this case is the same as where
Your question does not make much sense to me
So what if TSHSH certain rows might have no corresponding entries in S?
If you want just one of the joins to match
SELECT S.name
INTO #TempA
from tbl_Student S
LEFT OUTER JOIN tbl_StudentHSHistory TSHSH
on TSHSH.STUD_PK = S.STUD_PK
LEFT OUTER JJOIN tbl_CODETAILS C
on C.CODE_DETL_PK = S.GID
and #UseArchive = true
WHERE TSHSH.Begin_date < #BegDate
and ( TSHSH.STUD_PK is not null or C.CODE_DETL_PK id not null )

SQL Server 2008: Select then update statement

I'm doing a INNER JOIN across 6 tables for a module for my application, basically it takes the prostaff an gets their name and email, and compares that to a list of job applicants.
On the mod_employmentAppJobs I need to set a column for each row selected to true. Basically this sets a flag that tells the sql not to select the column because we already sent an email on that user. It's a bit field.
How do I set the emailSent field to true on a SQL statement? -- Coldfusion 8 is the Application server, just FYI....
SELECT *
FROM pro_Profile p
INNER JOIN pro_Email e ON p.profileID = e.profileID
INNER JOIN mod_userStatus m ON p.profileID = m.profileID
<!--- Joins the pro staff profiles to the employment app --->
INNER JOIN mod_employmentAppJobTitles a ON p.profileID = a.departmentID
<!--- Join Job titles to the jobs --->
INNER JOIN mod_employmentAppJobs b ON a.jobTitleID=b.jobTitleID
<!--- Joining the table on where the profile equals everything else --->
INNER JOIN mod_employmentAppProfile c ON c.eAppID = b.eAppID
WHERE b.emailSent = 'False'
You have a couple of choices.
1) Use a temp table and select data there first, update the mod_employmentAppJobs, and perform a select from the temp table to get your data retrieved.
So, it would look something like this.
create a temp table
CREATE TABLE #tmpTABLE
(
EmailAddress varchar(100),
JobTitle varchar(50),
JobTitleId bigint
......
)
Insert into it
INSERT INTO #tmpTable
SELECT EmailAddress,JobTitle, ........
FROM pro_Profile p
INNER JOIN pro_Email e
ON p.profileID = e.profileID
INNER JOIN mod_userStatus m
ON p.profileID = m.profileID
<!--- Joins the pro staff profiles to the employment app --->
INNER JOIN mod_employmentAppJobTitles a
ON p.profileID = a.departmentID
INNER JOIN mod_employmentAppJobs b
<!--- Join Job titles to the jobs --->
ON a.jobTitleID=b.jobTitleID
<!--- Joining the table on where the profile equals everything else --->
INNER JOIN mod_employmentAppProfile c
ON c.eAppID = b.eAppID
WHERE b.emailSent = 'False'
Update the source table (I'd recommend an index on jobTitleId in the temp table for performance if applicable)
UPDATE mod_employmentAddJobs
SET EmailSent="true"
FROM mod_employmentAppJobs b
INNER JOIN #tmpTable tmp
ON b.jobTitleID=tmp.jobTitleID
Get the actual data back to the app layer
SELECT * FROM #tmpTable
For better taste, I recommend sprinkling with BEGIN TRAN...COMMIT...ROLLBACK and BEGIN TRY..END TRY BEGIN CATCH...END CATCH to taste and to business requirements.
Also, it's good manners to drop the temp table after you are done with it, even though SQL server will not take offense if you don't.
2) You can use the OUTPUT clause of the update statement.
UPDATE mod_employmentAddJobs
SET EmailSent="true"
FROM pro_Profile p
INNER JOIN pro_Email e
ON p.profileID = e.profileID
INNER JOIN mod_userStatus m
ON p.profileID = m.profileID
<!--- Joins the pro staff profiles to the employment app --->
INNER JOIN mod_employmentAppJobTitles a
ON p.profileID = a.departmentID
INNER JOIN mod_employmentAppJobs b
<!--- Join Job titles to the jobs --->
ON a.jobTitleID=b.jobTitleID
<!--- Joining the table on where the profile equals everything else --->
INNER JOIN mod_employmentAppProfile c
ON c.eAppID = b.eAppID
WHERE b.emailSent = 'False'
OUTPUT inserted.*
This should get you the resultset right back to your app layer
You could store the result in a temporary table. You can use the data in the temporary table, and still return it at the end. It's a lot of typing but pretty straightforward:
-- Select data into temporary table
declare #result table (jobTitleID int, ...)
INSERT #result
(jobTitleID, ...)
SELECT jobTitleID
FROM pro_Profile p
...
-- Update unreadMail flag
update mod_employmentAppJobs
set unreadMail = 'False'
where jobTitleID in (select jobTitleId from #result)
-- Return result to application
select jobTitleId, ...
from #result
If you need to update and then return the data then probably the best is to use a Stored Procedure, where you first query the data, update it and then return it.
Well, this is just an idea, not the best solution.
You could get data (for which bit is false) in a DataReader and then execute a Command setting bit to true for ids contained in Dataset.
Dataset returns data you need...
I just tacked a on the end and it worked:
UPDATE mod_employmentAppJobs
SET emailSent = 'True'