How to drop this custom type? - sql

New to SQL, working on a databases project. I have two custom types, changedat and changedby defined by the following code:
CREATE TYPE [dbo].[changedat] FROM [smalldatetime] NULL
GO
CREATE TYPE [dbo].[changedby] FROM [nvarchar](30) NULL
GO
I'm working on my rollback script and not sure how to drop these types. They don't show up in sys.objects.

DROP TYPE dbo.changedat;
DROP TYPE dbo.changedby;
GO;

Look at the sql-server doc there you can see that you have ro use
DROP TYPE [ schema_name. ] type_name [ ; ]

Related

Set my function as Default

i have function and i want to create it as default
ALTER FUNCTION [dbo].[ModifiedBy]()
RETURNS varchar(50)
AS
BEGIN
RETURN host_name()
END
I want to do something like this, but it doesnt work. is it possible?
create default default_modifiedBy AS dbo.ModifiedBy()
Eror is User-defined functions, partition functions, and column references are not allowed in expressions in this context.
I have just tried doing this and it works fine for me:
CREATE FUNCTION [dbo].[ModifiedBy]()
RETURNS varchar(50)
AS
BEGIN
RETURN host_name()
END
GO
CREATE TABLE Test (
ID INT
, Hostname VARCHAR(50) DEFAULT ([dbo].[ModifiedBy]())
);
GO
Test
INSERT INTO dbo.Test ( ID )
VALUES ( 1 )
SELECT * FROM dbo.Test
From the MSDN page for create default:
Any constant, built-in function, or mathematical expression can be
used, except those that contain alias data types. User-defined
functions cannot be used
Like M.Ali writes, you can use a user-defined function if you create a column-bound default constraint with alter table ... add constraint or create table ... (col1 default dbo.MyFunc());.

Why a function (which is used as default constraint of a column in a table) cannot be changed?

I am working with SQL Server 2008 R2. I have a scalar-valued function which I need to modify. So I created a script which drops that function and then create it again.
When I run the script SQL Server gives me an error:
Msg 3729, Level 16, State 1, Line 2
Cannot DROP FUNCTION 'dbo.udf_GetCurrentUserId' because it is being referenced by object 'DF__generated__creat__02D4B8E6'.
I investigated and find out that this function is being used as a default constraint for a column in a table.
create table generated_email
(
generated_email_pk bigint not null identity,
name varchar(64) not null,
row_version RowVersion not null,
create_user varchar(50) default coalesce(dbo.udf_GetCurrentUserId(),user) not null,
create_datetime datetime default getDate() not null,
update_user varchar(50) default coalesce(dbo.udf_GetCurrentUserId(),user) not null,
update_datetime datetime default getDate() not null
)
I thought ok lets just modify the function. So I created a script which alter that function.
When I run the script SQL Server I get another error:
Msg 3729, Level 16, State 3, Procedure udf_GetCurrentUserId, Line 68
Cannot ALTER 'dbo.udf_GetCurrentUserId' because it is being referenced by object 'DF__generated__creat__02D4B8E6'.
Damn. So I am stuck. Why SQL Server implemented this restriction? Why it thinks that if a function is created it will never need modification?
That's silly that you can't change a function when it's being used in a constraint, but it seems to be a legitimate limitation in SQL Server. You could create a function such as
CREATE FUNCTION dbo.udf_GetCurrentUserIdCaller() AS varchar(8000)
BEGIN
RETURN dbo.udf_GetCurrentUserId()
END
Then your work of unloading and reloading constraints gets reduced to changing all constraints to use dbo.udf_GetCurrentUserIdCaller(), and then you can edit udf_GetCurrentUserId() all you like. SQL Server does not check nested dependencies.
You can programmatically access constraint text to get the information you need to script a solution from
SELECT obj.name as 'Table', col.name as 'Column',object_name(default_object_id) AS [ConstraintLabel],
object_definition(default_object_id) AS [DefaultValue]
FROM sys.objects obj INNER JOIN sys.columns col
ON obj.object_id = col.object_id
where obj.type = 'U' and object_definition(default_object_id) is not null

ADO.Net Table-Valued Parameter (TVP): Operand type clash: datetime2 is incompatible with int

I am working with a TVP, and I am trying to pass a data table to the stored procedure as a TVP. When the command tries to ExecuteNonQuery(), it throws an error:
Operand type clash: datetime2 is incompatible with int. The data for table-valued parameter "#tvpPermitWork" doesn't conform to the table type of the parameter.
I checked the data table using the visualizer, and I've found all of the data to be correct. I am now stuck and I don't have the time to change it to stored procedures with individual parameters.
Any suggestions on how to fix this is greatly appreciated.
I've found the solution for this issue.
You need to check the matching columns' order in your TVP and C# code.
For example, if you have the TVP like this:
CREATE TYPE [dbo].[tvp_FinDocContract] AS TABLE(
[column_1_Id] [uniqueidentifier] NOT NULL,
[column_2_Id] [uniqueidentifier] NULL,
[column_3_Id] [datetime] NULL
)
Then the C# code for creating the TVP must be like this:
DataTable tvp = new DataTable();
// The column order is very important
tvp.Columns.Add(new DataColumn("column_1_Id", typeof (Guid)){AllowDBNull = false};
tvp.Columns.Add("column_2_Id", typeof (Guid));
tvp.Columns.Add("column_3_Id", typeof (DateTime));
foreach (var item in ...)
{
//just populating
}
It's SQL fault, table types insert without column in .NET. You should create your same order with your table type. As you can see on sample.
I spend two day for this.
declare #p1 dbo.typeSoftCopyDocument
insert into #p1 values(275,491196,N'000001.tif',1,100,5330900910,'2018-09-06 14:49:18',111111,N'xxx',N'xxxx')
Sometime it occurred if table valued parameter not passed as per SQL TVP column order.
It should have same ordering in .NET & SQL
[id] [int] NULL,
[appStatus] [varchar](10) NULL,
[lodgedBy] [varchar](10) NULL,
.NET
objSearch = new AppSearchEN();
objSearch.id= context.Request["AppCat"].ToNullableInteger();
objSearch.appStatus= context.Request["AppStatus"] == "0" ? null : context.Request["AppStatus"];
objSearch.lodgedBy= context.Request["lodgedBy"] == "0" ? null : context.Request["lodgedBy"];
Then While passing parameter in .NET it must have same order of the parameter to table valued fn
It's hard to know exactly what's happening without seeing your code, but as a quick guess, have you set SqlParameter.SqlDbType = SqlDbType.Structured , and SqlParameter.TypeName = "YourTableType" ?
If so, what does the generated T-SQL look like (you can see it with SQL Profiler)?
How is your table type declared? -- CREATE TYPE YourTableType as TABLE ( ... )
How is your stored procedure declared? -- CREATE PROC ... #arg YourTableType READONLY ... AS ...
How is your DataTable configured? It should include something like:
yourDataTable.Columns.Add("columnName", typeof(datetime2));

Why is my table name not valid?

Here is the create statement:
create table dbmonitor.DBMON_DATABASE_TYPE (
DATABASE_TYPE_ID BIGINT IDENTITY NOT NULL,
DispName NVARCHAR(255) null,
primary key (DATABASE_TYPE_ID)
)
and this is the error I get:
13:40:57,685 ERROR [TestRunnerThread] SchemaExport [(null)]- The table name is not valid. [ Token line number (if known) = 1,Token line offset (if known) = 24,Table name = DBMON_DATABASE_TYPE ]
The table name is not valid. [ Token line number (if known) = 1,Token line offset (if known) = 24,Table name = DBMON_DATABASE_TYPE ]
Possibilities:
Is dbmonitor the name of your database? You can't put a . in a table name.
Do you mean CREATE TABLE dbmonitor.dbo.DBMON_DATABASE_TYPE?
Did you try CREATE TABLE DBMON_DATABASE_TYPE?
I'm not sure if dbmonitor is meant to be a schema name, but according to the documentation for the SQL CE CREATE TABLE statement, you cannot include a schema name with the table name.
Contrast this for SQL Server 2005 Compact Edition (just showing the initial part of the statement),
CREATE TABLE table_name
( { < column_definition > | < table_constraint > } [ ,...n ]
)
with this for SQL Server 2008:
CREATE TABLE
[ database_name . [ schema_name ] . | schema_name . ] table_name
This may not be exactly an answer for this question's criteria , but for those who might get here :
this error can also happen when you try to use EntityFramework.Extended library with Sql Server CE. It seems that they are not compatible.
check these links :
https://github.com/loresoft/EntityFramework.Extended/issues/35
https://github.com/loresoft/EntityFramework.Extended/issues/11

SQL Error Alter Table?

I have been trying to add columns to a table using some logic that produces this statement:
ALTER TABLE Master_List
ADD COLUMN Service VARCHAR(100) ,
Vendor VARCHAR(100) ,
Product VARCHAR(100) ,
Service_Description VARCHAR(100) ,
Level/Scale VARCHAR(100) ,
SunGard_Contract_Schedule_ID VARCHAR(100) ,
Application_Owner VARCHAR(100) ,
Application_Servers VARCHAR(100) ,
Required_Support/Dependencies VARCHAR(100);
whenever I have been trying to run it I continually get this error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(JdbcOdbc.java:3110)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(JdbcOdbcStatement.java:338)
at sun.jdbc.odbc.JdbcOdbcStatement.executeUpdate(JdbcOdbcStatement.java:288)
at Testing.main(Testing.java:54)
I have been checking online for the proper format for the ALTER TABLE command, and the formatting seems to be correct, I have tried changing so many things I have run out of ideas of how to fix it....
The table name is Master_List, and none of those columns already exist inside it.
This is being used inside Java, incase that is relevant.
It could be the / in your column names that is giving you the problem
Your column names contain the "/" character, and that is not a valid character for column names.