向表中添加一列,其默认值等于现有列的值 [英] Add a column to a table with a default value equal to the value of an existing column

查看:36
本文介绍了向表中添加一列,其默认值等于现有列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向 SQL Server 表中添加默认值等于现有列值的列?

How to add a column to a SQL Server table with a default value that is equal to value of an existing column?

我试过这个 T-SQL 语句:

I tried this T-SQL statement:

ALTER TABLE tablename 
ADD newcolumn type NOT NULL DEFAULT (oldcolumn) 

但它给出了一个错误:

在此上下文中不允许使用名称oldcolumn".有效的表达式是常量,常量表达式,并且(在某些上下文)变量.不允许使用列名.

推荐答案

试试这个:

ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0)
Go
Update tablename SET newcolumn = oldcolumn Where newcolumn = 0
Go

这篇关于向表中添加一列,其默认值等于现有列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆