I check for the existence of a column in a table. If it exists, I update a column in a 2nd table based on the column in first table.
The issue is, the update is getting executed when it should not be and results in an error.
I check for the existence of column Requested_by
in table Service_requests_details
, I then update a column in service_requests
based on column requested_by
in table Service_Requests_Details
.
The point is, Requested_By
might not exist in table Service_requests_details
.
IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'Requested_By' and object_ID = object_ID(N'Service_Requests_Details'))
BEGIN
Update SR
Set SR.Requested_By = SRD.Requested_By
FROM Service_Requests SR
INNER JOIN Service_Requests_Details SRD ON SRD.Request_Index = SR.Service_Request_Index
END
GO
Update:
Thanks everyone who responded. Thanks @SqlAcid for the answer.
The problem is the parser will still evaluate your update statement and fail even when the IF EXISTS is false; you could use sp_executesql to get around it:
declare @sql nvarchar(1000)
IF EXISTS (SELECT * FROM sys.columns WHERE Name = N'Requested_By' and object_ID = object_ID(N'Service_Requests_Details'))
BEGIN
set @sql = 'Update SR
Set SR.Requested_By = SRD.Requested_By
FROM Service_Requests SR
INNER JOIN Service_Requests_Details SRD ON SRD.Request_Index = SR.Service_Request_Index'
exec sp_executesql @sql
END
GO
This is what I would do in SQL 2008, don't have a SQL 2005 instance handy to see if it works in there, but worth a try:
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Service_Requests_Details' AND COLUMN_NAME = 'Requested_By')
BEGIN
...
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.