0

How to set the default value of an attribute to the value of another attribute in another table using Visual Database Tools?

2
Contributors
7
Replies
8
Views
8 Years
Discussion Span
Last Post by sknake
0

What is an attribute in MSSQL? Are you sure you're asking in the right forum?

i have two tables

table A:
column B: some data

table C:
column D: default value taken from table A - column B

any suggestions please

0

Use a trigger to default the value if its null when inserting. That will allow you to use a custom query to fetch the values

0
/*
table A:
column B: some data

table C:
column D: default value taken from table A - column B
*/

IF OBJECT_ID('TableA', 'U') IS NOT NULL DROP TABLE TableA
Create Table TableA
(
  ColumnB varchar(50)
)

GO

Insert Into TableA (ColumnB) Values ('DefaultValue')

GO

IF OBJECT_ID('TableC', 'U') IS NOT NULL DROP TABLE TableC
Create Table TableC
(
  RecordId int identity(1000, 1) PRIMARY KEY NONCLUSTERED,
  ColumnJunk varchar(30),
  ColumnD varchar(50)
)

GO

IF OBJECT_ID ('TableC.DefaultValue', 'TR') IS NOT NULL
   DROP TRIGGER TableC.DefaultValue;
GO

CREATE TRIGGER DefaultValue
ON TableC
INSTEAD OF INSERT
AS 
BEGIN
  Insert Into TableC (ColumnJunk, ColumnD)
  Select i.ColumnJunk,
  (
    Select Top 1 ColumnB
    From TableA
  )
  From Inserted i
END

GO

Insert Into TableC (ColumnJunk) Values ('abc')

GO

Select *
From TableC
0

You're welcome

Please mark this thread as solved if you have found the answer to your original question and good luck!

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.