[英]Update a table column in SQL Server 2005
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
. 我检查列的存在
Requested_by
表Service_requests_details
,然后我在更新列service_requests
基于列的requested_by
表Service_Requests_Details
。
The point is, Requested_By
might not exist in table Service_requests_details
. 关键是,表
Service_requests_details
Requested_By
可能不存在。
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.
感谢@SqlAcid的答案。
The problem is the parser will still evaluate your update statement and fail even when the IF EXISTS is false; 问题在于,即使IF EXISTS为false,解析器仍然会评估您的更新语句,并且失败; you could use sp_executesql to get around it:
您可以使用sp_executesql来解决它:
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: 这就是我要在SQL 2008中执行的操作,没有方便的SQL 2005实例来查看它是否可以在其中运行,但是值得一试:
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Service_Requests_Details' AND COLUMN_NAME = 'Requested_By')
BEGIN
...
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.