SQL Server : Update with Where - sql-server

I'm still learning SQL and I've been scavenging the internet for a solution.. For some reason I can't grasp the concept for this query 100%. I've been on this for a few days and getting no where. I do apologize in advance, I'm sure this is pretty simple for most of you.
I have a table called dbo.personnelUDF and dbo.personnel table in the same database. The dbo.personnelUDF references back to dbo.personnel.personid. Basically, I need to find the value located in dbo.personneludf.employee_id_ and update the dbo.personneludf.active_fueler_ = '1'
This is what am I'm getting.. what am I doing wrong??
UPDATE dbo.PersonnelUDF
SET Active_Fueler_ = '1'
FROM dbo.PersonnelUDF AS a
INNER JOIN dbo.Personnel ON dbo.Personnel.ObjectID = dbo.PersonnelUDF.ObjectID
WHERE dbo.PersonnelUDF.Employee_ID_ = 123456
Error:
Msg 4104, Level 16, State 1, Line 4
The multi-part identifier "dbo.PersonnelUDF.ObjectID" could not be bound.
Msg 4104, Level 16, State 1, Line 5
The multi-part identifier "dbo.PersonnelUDF.Employee_ID_" could not be bound.

You have aliased the table and then havent used it, you can do the below
UPDATE dbo.PersonnelUDF
set Active_Fueler_ = '1'
from dbo.PersonnelUDF INNER JOIN dbo.Personnel
ON dbo.Personnel.ObjectID=dbo.PersonnelUDF.ObjectID
where dbo.PersonnelUDF.Employee_ID_=123456
OR
UPDATE A
set Active_Fueler_ = '1'
from dbo.PersonnelUDF AS A INNER JOIN dbo.Personnel
ON dbo.Personnel.ObjectID = A.ObjectID
where A.Employee_ID_=123456

The error is because you have aliased PersonnelUDF in the FROM clause "AS a". If you get rid of that, it should work.

Related

Bouncing Between Multi-Part Identifier Could Not Be Bound & Ambiguous Column Name

I keep getting two error messages depending on what I try to do to fix them.
Firstly here is my code:
SELECT
ConsltNum AS 'Consultant Number',
COUNT(ConsltNum) AS 'Client Count',
AVG(Balance) AS 'Average'
FROM
Client Cl
INNER JOIN
Consultant Cn ON Cl.ConsltNum = Cn.ConsltNum
GROUP BY
Cn.LastName
Upon running it, I get this.
Msg 209, Level 16, State 1, Line 3
Ambiguous column name 'ConsltNum'.
Msg 209, Level 16, State 1, Line 3
Ambiguous column name 'ConsltNum'.
Now, I know it is ambiguous because the ConsltNum exists in both tables I've included. Normally I'd try and dial into that database by changing the code to this:
SELECT
Client.ConsltNum AS 'Consultant Number',
COUNT(Client.ConsltNum) AS 'Client Count',
AVG(Balance) AS 'Average'
FROM
Client Cl
INNER JOIN
Consultant Cn ON Cl.ConsltNum = Cn.ConsltNum
GROUP BY
Cn.LastName
Upon running this, I get:
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Client.ConsltNum" could not be bound.
Msg 4104, Level 16, State 1, Line 3
The multi-part identifier "Client.ConsltNum" could not be bound.
A few other things worth mentioning: I've tried dialling to dbo.Client.ConsltNum and it throws the same error.
Just use the right alias:
SELECT cl.ConsltNum AS Consultant_Number,
COUNT(*) AS Client_Count, AVG(?.Balance) AS Average
FROM Client Cl INNER JOIN
Consultant Cn
ON Cl.ConsltNum = Cn.ConsltNum
GROUP BY cl.ConsltNum;
The ? is for the the alias of the table where balance comes from.
Notes:
You need to use the table alias assigned for the column.
The GROUP BY should match the SELECT column.
Only use single quotes for string and date constants. Give columns names that don't need to be escaped.
You might was well use COUNT(*), because you know ConsltNum is never NULL.

CASE STATEMENT for create view in SQL Server 2008

I have a create view query and I want to check if it does not exist yet, then create view. I tried to create like this:
CASE WHEN IS NOT EXISTS vw_Delays
THEN
VIEW vw_Delays AS
SELECT RD_RfileID_fk_ind, SUM(DATEDIFF(day, RD_Startdate, RD_EndDate)) AS delays FROM dbo.t_RfDelay
GROUP BY RD_RfileID_fk_ind
END
but it returns these errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'CASE'.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 'END'.
How to solve this? Please can anyone help me to fix this ?
You need to use this code to check for the view's existence:
IF NOT EXISTS (SELECT * FROM sys.views WHERE Name = N'vw_Delays')
.....
The next obstacle you'll encounter is the fact that the CREATE VIEW statement must be the first of a SQL batch - so you cannot have it right after the existence check.
What I usually do is the opposite:
check if the view does exist
and if so - drop the existing view
then create the view from scratch
and I use this code for this setup:
IF EXISTS (SELECT * FROM sys.views WHERE Name = N'vw_Delays')
DROP VIEW dbo.vw_Delays;
GO
CREATE VIEW dbo.vw_Delays
AS
SELECT
RD_RfileID_fk_ind,
SUM(DATEDIFF(day, RD_Startdate, RD_EndDate)) AS delays
FROM
dbo.t_RfDelay
GROUP BY
RD_RfileID_fk_ind

Invalid object name in SQL Join

I am switching to SQL Server from the visual editor approach I used in MS Access. Here is my first attempt. I am joining two tables and keep getting an invalid object. Where am I going wrong? The error message specifically says:
(560180 row(s) affected)
Msg 208, Level 16, State 1, Line 20
Invalid object name 'BillingTable'.
My query is:
SELECT [Tracking_Number]
,[Package_Key]
,[Manifest_Datetime]
,[Packed_Datetime]
,[Order_Number]
,[WMS_Order_Number]
,[Shipped_Warehouse_Name]
,[Carrier]
,[Service_Name]
,[Zone]
,[Estimated_Weight]
,[Estimated_Cost]
,[Preferred_Warehouse_Name]
,[WMS_Shipping_Method_Name]
FROM [Shipping].[dim].[tbl_Package] as PackageTable
where [Manifest_Datetime] > '1/1/2016'
SELECT [Invoice_Date_Key]
,[Order_Date_Key]
,[Package_Key]
,[Billed_Weight]
,[Billed_Weight_Metric]
,[Package_Quantity]
,[Total_Cost_Dollars]
,[Tax_Cost_Dollars]
,[Total_Cost_Billed_Currency]
FROM [Shipping].[fact].[tbl_Shipping_Billing] as BillingTable
JOIN BillingTable
on PackageTable.Package_Key = BillingTable.Package_Key
Your query should look like this:
Select PackageTable.*, BillingTable.*
From [Shipping].[dim].[tbl_Package] as PackageTable
Inner Join [Shipping].[fact].[tbl_Shipping_Billing] as BillingTable
on PackageTable.Package_Key = BillingTable.Package_Key
where PackageTable.[Manifest_Datetime] > '1/1/2016'
You can call out the specific fields you want from those tables instead of using the .*

SQL Server syntax error identifier could not be bound

Why is this SQL getting a syntax error and how can it be fixed?
UPDATE s
SET s.modified_date = l.action_date
FROM
(SELECT l.action_date, l.user_id FROM item_audit_log) l
WHERE l.user_id = s.staff_id
Error:
Msg 4104, Level 16, State 1, Line 4
The multi-part identifier "l.action_date" could not be bound.
Msg 4104, Level 16, State 1, Line 4
The multi-part identifier "l.user_id" could not be bound.
You are getting the error because your subquery references "l" in the subquery, but it is not defined inside the subquery (it is defined in the outer scope). However, you don't need the subquery:
UPDATE s
SET modified_date = l.action_date
FROM staffs s JOIN
item_audit_log l
ON l.user_id = s.staff_id;
This assumes you have a table called s. I imagine that this really should be an alias, also defined in the FROM clause.
As your request is "WHY" this occurs, let me clarify it :
This error usually occurs when an alias is used when referencing a
column in a SELECT statement and the alias used is not defined
anywhere in the FROM clause of the SELECT statement.

Create Table As With

Im writing sql query and i have issue which i cannot fix.
I'm trying this:
CREATE TABLE a
AS
WITH cteCandidates (Miejscowosc, Ulica, NrDomu, KodPocztowy)
AS
(
SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy
FROM Gimnazja
INTERSECT
SELECT Miejscowosc, Ulica, NrDomu, KodPocztowy
FROM SzkolyPodstawowe
)
Select
e.Lp as 'Gimnazja',
s.Lp as 'Szkoly Podstawowe'
FROM
Gimnazja AS e
INNER JOIN cteCandidates AS c
ON e.Miejscowosc = c.Miejscowosc AND e.Ulica = c.Ulica AND e.NrDomu = c.NrDomu AND e.KodPocztowy = c.KodPocztowy
INNER JOIN SzkolyPodstawowe s
ON s.Miejscowosc = e.Miejscowosc AND s.Ulica = e.Ulica AND s.NrDomu = e.NrDomu AND s.KodPocztowy = e.KodPocztowy
Order By 'Gimnazja'
And errors which i get:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'AS'.
Msg 319, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
And i don't know why. I think that my query is proper but clearly not, and i don't understand why.
Perhaps you want:
WITH cteCandidates (...)
SELECT
e.Lp as 'Gimnazja',
s.Lp as 'Szkoly Podstawowe'
INTO a -- < -- table created here
FROM
Gimnazja AS e
INNER JOIN ...;
CREATE TABLE is used to define a table schema. The WITH keyword is used to define a CTE retrieval of data. These are two completely different operations.
If you need a table within your SQL look at http://msdn.microsoft.com/en-us/library/ms174979.aspx to see the syntax for defining it. You then may populate it with INSERT but that's highly unlikely to be from a CTE ( see below)
Usually with CTEs you don't need to insert the data into a table; in the statement immediately after it you can just use the data retrieved as the table has been temporarily defined and populated for you automatically.
A CTE can be used to define a VIEW - see Create view based on hierarchy / used of CTE for an example
Are you trying to create a view? Then it'd work...

Resources