SQL Server行间交换数据问题
我向 b4 询问有关交换查询以在同一个表中的行之间交换数据的信息,我得到了该查询。
ALTER PROCEDURE [dbo].[VehicleReservationsSwap]
(@FirstVehicleID int,
@secondVehicleID int,
@WhereClause nvarchar(2000))
AS
BEGIN
Create Table #Temp (VehicleID int,
VehicleType nvarchar(100),
JoinId int)
DECLARE @SQL varchar(8000)
SET @SQL = 'Insert into #Temp (VehicleID, VehicleType, JoinId) SELECT
VehicleID,VehicleType,CASE WHEN VehicleID = ' + Cast(@FirstVehicleID as varchar(10)) + ' then ' + Cast(@secondVehicleID as varchar(10)) + ' ELSE ' + Cast(@FirstVehicleID as varchar(10)) + ' END AS JoinId
FROM Reservations
WHERE VehicleID in ( ' + Cast(@FirstVehicleID as varchar(10)) + ' , ' + Cast(@secondVehicleID as varchar(10)) + ' )' + @WhereClause
EXEC(@SQL)
--swap values
UPDATE y
SET y.VehicleID = #Temp.VehicleID,
y.VehicleType = #Temp.VehicleType
FROM Reservations y
INNER JOIN #Temp ON y.VehicleID = #Temp.JoinId
WHERE y.VehicleID in (@FirstVehicleID, @SecondVehicleID)
Drop Table #Temp
END
此查询需要 2 个参数,并且正在交换为每个参数返回的所有行。
问题是,如果每个参数(外键)都有值,查询就会交换 如果其中一个没有价值,我需要进行交换。
我希望有人能在这方面帮助我。
谢谢,
I was asking b4 about swapping query to swap data between rows in same table and I got that query
ALTER PROCEDURE [dbo].[VehicleReservationsSwap]
(@FirstVehicleID int,
@secondVehicleID int,
@WhereClause nvarchar(2000))
AS
BEGIN
Create Table #Temp (VehicleID int,
VehicleType nvarchar(100),
JoinId int)
DECLARE @SQL varchar(8000)
SET @SQL = 'Insert into #Temp (VehicleID, VehicleType, JoinId) SELECT
VehicleID,VehicleType,CASE WHEN VehicleID = ' + Cast(@FirstVehicleID as varchar(10)) + ' then ' + Cast(@secondVehicleID as varchar(10)) + ' ELSE ' + Cast(@FirstVehicleID as varchar(10)) + ' END AS JoinId
FROM Reservations
WHERE VehicleID in ( ' + Cast(@FirstVehicleID as varchar(10)) + ' , ' + Cast(@secondVehicleID as varchar(10)) + ' )' + @WhereClause
EXEC(@SQL)
--swap values
UPDATE y
SET y.VehicleID = #Temp.VehicleID,
y.VehicleType = #Temp.VehicleType
FROM Reservations y
INNER JOIN #Temp ON y.VehicleID = #Temp.JoinId
WHERE y.VehicleID in (@FirstVehicleID, @SecondVehicleID)
Drop Table #Temp
END
This query takes 2 parameters and is swapping all rows returned for each parameter.
The problem is the query swaps just if each parameter (foreign key) has values
I need to make swapping in case if one of them has no value.
I hope if some one can help me in that.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我得到了它
I got it