2006/07/22

Querying a view in another view, column datatypes & a 'String or binary data would be truncated' error

When you query a view (a child view) inside another view (a parent view), always remember to recreate the latter one when you change a datatype of a column in the former one.

An example:

-- a child view
CREATE VIEW dbo.FOO
AS
  SELECT 'a' AS A
GO

-- a parent view
CREATE VIEW dbo.BAR
AS
  SELECT *
  FROM dbo.FOO
GO

sp_help BAR
-- column A has a datatype of varchar(1)
-- Column_name  Type       Computed   Length
-- ------------ ---------- ---------- ------- [...]
-- A            varchar    no         1

DROP VIEW dbo.FOO
GO

CREATE VIEW dbo.FOO
AS
  SELECT 'aa' AS A
GO

sp_help BAR
-- sp_help still shows that column A has a datatype
-- of varchar(1), although it is now varchar(2) - see
-- the SELECT statement below
-- Column_name  Type       Computed   Length
-- ------------ ---------- ---------- ------- [...]
-- A            varchar    no         1

SELECT *
FROM dbo.BAR
-- A
-- ----
-- aa

If you now try to run the following query:

  SELECT *
  INTO dbo.NEW_TABLE
  FROM dbo.FOO

it will fail with an String or binary data would be truncated error.

No comments:

Post a Comment