SQL - Setting parameters for Default Column Value in Table - sql

Using SQL Server 2012.
I have a column in my member table that is created using the following script:
[EnableMemberWebAccess] [bit] NOT NULL DEFAULT ((1))
I want this column to only have 1 as a default if another column in this same table is a certain value. Let's call this column MemDesc, and I want the EnableMemberWebAccess to be defaulted to 1 when MemDesc = 'Founder', and for it to default to 0 when MemDesc != 'Founder'.
Any help much appreciated!

There is probably no way to achieve a default value that can be changed afterwards. Either you have a value that you insert in the beginning. You will then need to take care of consistency within the application:
ALTER TABLE *table* ADD COLUMN EnableMemberWebAccess bit NULL
UPDATE *table* SET *table.*EnableMemberWebAccess = CAST(CASE WHEN *table*.MemDesc = 'Founder' THEN 1 ELSE 0 END AS bit)
ALTER TABLE *table* ALTER COLUMN EnableMemberAccess bit NOT NULL
Or you have to use a computed column. This will not allow you to change the value of the column except if you change the value of the column it depends on.

Computed column should work for you:
ADD EnableMemberWebAccess AS cast((CASE WHEN MemDesc='Founder' THEN 1 ELSE 0 END) as bit)

Related

Handling null for char(1) and varcar(2) in hive

I am reading a flat file in hive and i have null values coming in file like below
a|b|null|null|d
and when I create table on top of this with below datatypes
a char(1),b char(1),c char(1),varchar2(2),char(1)
and the value in table coming like this
a,b,n,nu,d
The oneway I can do this is to make the datatype as varchar2(4) and add check at null.
But is there any other way i can do this.
SerDe treats 'null' strings as normal values, no difference between value 'a' and 'null'.
Try to add 'serialization.null.format'='null' property to your table definition:
ALTER TABLE mytable SET tblproperties('serialization.null.format'='null');
Another approach is to use STRING data type and case statements is select:
select case when col = 'null' then null end as col
...

Microsoft SQL int type take not negative value

I have a problem. I created a table in Microsoft SQL and I would like one column to take not negative values. For example, EmployeeSalary column type is int and it hasn't a negative value.
Here is the solution of your problem:
Use CHECK while creating Table like this:
CREATE TABLE Table_name
(
col1 int CHECK (col1 >= 0)
)
OR
If you want to make a column to reject negative number, after creating the table then you can do like this:
ALTER TABLE Table_Name ADD CONSTRAINT constraint_name CHECK (col_name >= 0);
If you want to set condition when creating the table try:
EmployeeSalary money CHECK (EmployeeSalary>= 0)
If you just want to check during some script execution you can use if :
if(#Var > 0) begin
....
end
go tools>options>designer
"prevent changes that require table re-creation" this one should be unchecked.

user defined function (TSQL) non deterministic and computed persisted column

I have a table, which among it's columns there are two columns of type INT and they are called:
ExpirationMonth
and
ExpirationYear
I want to add a new column to this table, whose value will be calculated based on the values of ExpirationMonth and ExpirationYear. So this column would be a computed column.
For this purpose, I have created a user defined scalar function that calculates the value of this column based on the values of ExpirationMonth and ExpirationYear. The defintion of the function is the following:
CREATE FUNCTION [dbo].[IsExpired]
(
#ExpirationMonth INT,
#ExpirationYear INT
)
RETURNS BIT
AS
BEGIN
DECLARE #Today DATE = GETDATE()
DECLARE #PreviousMonth INT = MONTH(#today)-1
DECLARE #CurrentYear INT = YEAR(#today)
DECLARE #IsExpired BIT = 0
IF(#ExpirationYear<#CurrentYear OR
(#ExpirationYear=#CurrentYear AND #ExpirationMonth<=#PreviousMonth))
SET #IsExpired = 1
RETURN #IsExpired
END
Initially, I tried to add the column as below:
ALTER Table_Name
ADD IsExpired AS [dbo].[IsExpired]([ExpirationMonth], [ExpirationYear]) PERSISTED
And I got the following error:
Computed column 'IsExpired' in table 'Table_Name' cannot be persisted
because the column is non-deterministic.
I removed the PERSISTED from the above statement and I ran it again. Then I noticed that the column had been added with the expected values.
My question is how can I make this column to be persisted, if that is possible at all?
I realized that the reason for this error is the usage of the GETDATE function in the IsExpired function. Since GETDATE is not deterministic, the IsExpired is not deterministic.
However, I don't see how we could make this function, IsExpired, to be deterministic and as a result to define the computed column as persisted, if that is possible at all.
Could you please tell me if that's possible and if it is, how can I do this.
The value is nondeterministic because it's dependent on the current date. You can't persist computed columns whose values can change over time.
See this article on MSDN for more information on Deterministic Functions.
I would suggest doing it in a view
SELECT * INTO yourTable
FROM (VALUES(2015,1),(2015,2),(2015,3),(2015,4),(2015,5),(2015,6)) AS A(ExpirationYear,ExpirationMonth);
GO
CREATE VIEW vw_Expiration
AS
SELECT ExpirationYear,
ExpirationMonth,
CASE
WHEN ExpirationYear < YEAR(GETDATE()) OR
(ExpirationYear = YEAR(GETDATE()) AND ExpirationMonth <= MONTH(GETDATE()))
THEN 1
ELSE 0
END AS IsExpired
FROM yourTable;
GO
SELECT *
FROM vw_Expiration
Results:
ExpirationYear ExpirationMonth IsExpired
-------------- --------------- -----------
2015 1 1
2015 2 1
2015 3 1
2015 4 1
2015 5 0
2015 6 0

Using Cell content as a parameter of a Function in SQL Server Query

I just Started working with SQL Server and I want to set one column of my table based on another column(automatically and both columns are in a same table). I've wrote a function like this:
ALTER FUNCTION [dbo].[FloorNameConvertor]
(
#Number int
)
RETURNS nchar(10)
AS
BEGIN
RETURN
( CASE
WHEN #Number/100=1 THEN 'x'
WHEN #Number/100=2 THEN 'y'
ELSE 'w'
END
)
END
and I use it in default value of my column properties. I have problem to send a value of the cell as a parameter ( I can't select one cell )?
Thanks
You cannot use other column names in default constraints. You can work it around with INSTEAD OF INSERT trigger or use computed column (not persisted though).

How do I set a column value to NULL in SQL Server Management Studio?

How do I clear the value from a cell and make it NULL?
I think Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.
If you've opened a table and you want to clear an existing value to NULL, click on the value, and press Ctrl+0.
If you are using the table interface you can type in NULL (all caps)
otherwise you can run an update statement where you could:
Update table set ColumnName = NULL where [Filter for record here]
Use This:
Update Table Set Column = CAST(NULL As Column Type) where Condition
Like This:
Update News Set Title = CAST(NULL As nvarchar(100)) Where ID = 50
Ctrl+0 or empty the value and hit enter.
Just as a little extension to Jeff Martin's and Zack Peterson's solution.
If you still want to set several values from the columns to null you can simply set the query to
UPDATE myTable SET MyColumn1 = NULL, MyColumn2 = NULL, MyColumn3 = NULL, ...
CTRL+0 doesn't seem to work when connected to an Azure DB.
However, to create an empty string, you can always just hit 'anykey then delete' inside a cell.