0

我有一个包含楼层名称的表格,我需要用数值替换它。我正在手动构建一个查找表。不知道下一步该怎么做...有更好的方法吗?

截图:http: //i49.tinypic.com/2mc921e.png

BEGIN TRY
BEGIN TRANSACTION

-- lookup table
DECLARE @FloorLkup TABLE(
    FloorName VARCHAR(MAX) NOT NULL,
    FloorNum INT NOT NULL
);

INSERT INTO @FloorLkup SELECT 'First floor', '1'
INSERT INTO @FloorLkup SELECT 'First', '1'
INSERT INTO @FloorLkup SELECT 'Second floor', '2'
INSERT INTO @FloorLkup SELECT 'Second', '2'
-- etc.
INSERT INTO @FloorLkup SELECT 'Ninth', '9'

print 'Done'
COMMIT TRANSACTION
END TRY
BEGIN CATCH
print 'Did not work'
ROLLBACK
END CATCH

另外,问题是:某些楼层被命名为FirstandFirst floor等。

4

1 回答 1

1
-- populate your @FloorLkup table here

-- now add a new numeric column:
ALTER TABLE dbo.UnknownTableName
  ADD FloorNumber INT;

-- now update based on matches in @FloorLkup
UPDATE t
  SET FloorNumber = fl.FloorNum
  FROM dbo.UnknownTableName AS t
  INNER JOIN @FloorLkup AS fl
  ON t.FloorName = fl.FloorName;

-- check your work
SELECT * FROM dbo.UnknownTableName;

-- if it's correct:
ALTER TABLE dbo.UnknownTableName
  DROP COLUMN FloorName;

您必须UnknownTableName用目标表的名称替换,因为您忘了告诉我们。您可能还需要删除任何约束或对FloorName列的其他显式引用,然后才能删除它。

也请不要害怕元音或更长的名字。Lookup并且FloorNumber实际上比andLkup更容易输入FloorNum

于 2013-03-13T14:42:01.227 回答