Modifying a function used as a column default in SQL Server - sql

We're having an issue with a poorly coded SQL function(which works fine in live, but not in our test environment). This function is used to provide a default value in many tables, trying to ALTER the function returns a "Cannot ALTER ### because it is being referenced by object" error.
Is there any way round this error message? The only way I can think of is attempting to write a script to remove it from every table that has it as a default, altering the function and re-adding it after.

Since the object is referenced, you cannot modify it. This is what you do:
Remove the default constraint from the table/column
Modify the function
Add the default constraint back

SQL Server will not allow you to modify a function that is bound to the DEFAULT constraint of a column.
Your only option is to remove the constraint before altering the function. (Source)

Related

sql replace by default

Is it possible to define a constraint on a column that will replace a certain input value by a default value?
I have a table with a type column that should always be a default value unless the user defines the type of the feature.
When the type is NULL, it will be replaced by the default value. Unfortunately the form handler does not fill in NULL when type is not defined. It fills an empty string instead.
How can I program SQL to replace these empty strings by the default value?
Code snip:
CREATE TABLE [dbo].[ACC_Plannen](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PLANID] [nchar](50) NULL,
[plantype] [nvarchar](500) NULL CONSTRAINT [DF_ACC_Plannen_plantype] DEFAULT ('Algemeen'),
If you can only handle this on SQL, you can try few things:
Create a stored procedure that will clean up input and insert/update your table;
Create an insert/update trigger that will fix values for you.
Between the two above I'd go with stored procedure, because you have to explicitly call it while trigger does it's work implicitly. Might even add a trigger that raises error on invalid input instead of fixing it.
Ideally you would clean input before sending it to SQL though. Then you could just have NOT NULL DEFAULT constraint on your table.
The main question is the following: "Do you want to reject the insert and fix the data at the front end (user/application prgm). Or just update the bad data on the back end (database)."
A check constraint can be used to valid the data and make sure there is not empty string. A violation results in a error.
A after insert trigger can be used to re-work (update) the empty string into what ever value you want.
Just be cognizant of the use case.
If you are bulk inserting and a check constraint fails, the whole batch is aborted.
If you are inserting a large amount of data, the trigger will be executed for each record. Maybe a update statement after a large batch load in warranted in this case.
As always, it depends on your situation.
Happy coding!

Default constraint with synonym or UDF from other database

Is it possible to add default constraint with synonym or UDF from other database?
Create table TestTable (
ID int identity(1,1),
SData varchar(100),
UserName varchar(100) default [OtherDatabaseName].dbo.fn_Test('value'))
Below is the error message, while I am trying to add default constraint
The name "OtherDatabaseName" is not permitted in this context. Valid
expressions are constants, constant expressions, and (in some
contexts) variables. Column names are not permitted.
We can add UDF from same database but I want add UDF from other database. Because it is used in multiple databases on same server.
And I do not want to create that UDF in all database and prevent duplicate code.
Please let me know if there is any other/better way. Thank you.
Please let me know if there is any other/better way.
One other way would be to use a trigger instead of a default.

Microsoft Access - SQL command to add a constraint

I Am new in stackoverflow and whats worst is I am new to Microsoft Access. My homework
Assume the Part table has been created, but there are no integrity constraints. Create the necessary integrity constraint to ensure that the only allowable values for the Class field are AP, HW, and SG. Ensure that the PartNum field is the primary key and that the PartNum field in the OrderLine table is a foreign key that must match the primary key of the Part table.
So I know how to create this by using Microsoft Access by going to the Validation Rule and add validation for AP, HW, and SG. However, I need to also create the query to show how this is done.
My code:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK IN Class(AP, HW, SG)
;
My textbook has an example which is similar to what I just wrote above. When I run this I get a Constraint error. What am I doing wrong? Also, the foreign key and primary key have already been made so I just need to write the sql query to display my result. Any help is appreciated!
The CHECK clause exists but it's not a particularly good idea to use it because it can create issues in you application.
That being said, your constraint should work but there are a couple things:
You should avoid the use of the word Class as a field name. It's not a reserved word per se, but it's a VBA reserved word and while Access let you create that field, you may encounter strange problems elsewhere later.
As Brian said, you need to use single quotes for string literals in your CHECK
You can't create CONTRAINT with CHECK from the SQL Query Editor in Access, you'll get errors on the CHECK part every time you try.
Instead you need to execute the DDL SQL from VBA: just open the VBA (Alt+F11) then type the following in the Immediate Window (Ctrl-G if you don't see it), then press ENTER:
CurrentProject.Connection.Execute "ALTER TABLE Parts ADD CONSTRAINT ClassRule CHECK (Class IN ('AP', 'HW', 'SG'));"
If you don't get an error, then the constraint was properly executed, otherwise, double check that the syntax is correct, field names, parenthesis are properly balanced, and that the Part table is not open.
You probably want:
ALTER TABLE Parts
ADD CONSTRAINT classRule
CHECK (class in ('AP', 'HW', 'SG'));
There is a space between CONSTRAINT and the name
Put conditions within the () after the CHECK keyword
Put literals within single quotes, as this is what differentiates field names from values
Edit
Although the above is valid syntax, from what I'm reading you may not be able to add a check constraint in Access via writing out the SQL, at least not in the SQL view of query designer.
You can add a check constraint by going to Design View for the table of interest, then on the row representing the column of interest, type the following on the line for "Validation Rule":
in ('AP', 'HW', 'SG')
http://www.databaseskill.com/1942875/
"Note The check constraint statement can only be executed through the Jet OLE DB provider and ADO; it will return an error message if used though the Access SQL View user interface."
Above quote is from the URL I just provided.

How to include the clients ip adress in to an audit as default constrain in sqlserver

Am writing av analytical standard solution register from the doping laboratory that i work for and got stuck on the problem how to get the ipaddress of the client in to the audit table.
I have found a straight forward method for actually get the ipaddress on the web and my question is not about that.
I got triggers on every table inserting records in to the audit table and I do not want to wright the inserting of the ipaddress manualy in every trigger. I would like to have something like a DEFAULT Constraint do the actual insertion of the ipaddress, but when I try I get errors about sub Queries not allowed.
Here is the way to get the address,
SELECT client_net_address
FROM sys.dm_exec_connections
WHERE (session_id = ##SPID)
You can use a SQL function as the DEFAULT constraint
http://msdn.microsoft.com/en-us/library/ms186755.aspx.
If using SQL isnt enough, you can use a CLR function as a default constraint.
http://msdn.microsoft.com/en-us/library/ms186755.aspx
The documentation specifies that a DEFAULT constraint can be "a constant, NULL, or a system function". Since there is no system function that returns the net address of the client, you cannot do what you want directly.
A trigger is the obvious solution here. Audit triggers are often created and maintained automatically from a template anyway, because they are usually identical on all tables, and if you aren't doing this already then perhaps this would be a good opportunity to start. That would avoid your issue with manually adding the code everywhere.

null values in mySQL

I've got a new website moved to my server. This website uses PHP and MySQL, and is built very poorly.
The problem is - it needs non-null values inserted into new records where ever I don't specify a value, though the default value is null.
I've been told it has been done on the previous server, but they have no idea how. I'd be glad to receive some help on this.
You could update the default values of the fields of your database to prevent problems using:
ALTER TABLE `table` ALTER `field` SET DEFAULT 'value'
More information on ALTER TABLE for specific fields and parameters can be found in the documentation.
You need to add default values for the columns, either recreate the tables with defaults or alter the table definitions.
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
http://dev.mysql.com/doc/refman/5.1/en/create-table.html