I am trying to insert null with my query into a datetime column which allows null. My query works fine (I think). But its putting 1900-01-01 00:00:00.000 instead of null into the datetime column. Why is this happening and how do I fix it ?
I created my own table to test this and nulling is NOT a problem there. But, it is a problem in another database. I think it must be something to do with the other database.
When inserting using INSERT query, don't specify the column name and don't give any value. That should insert null in the field.
For example, If Entry_Date is my nullable datetime column in abc table, then my insert statement would be like:
Insert into abc (Entry_Id, Entry_Value) values (1,1000);
By not mentioning the column, it should have null in it. Hope it helps.
To see all the triggers in the database, use the following query:
select
t.name as [TableName],
tr.name as [TriggerName],
m.[definition]
from sys.triggers tr
join sys.sql_modules m on m.object_id = tr.object_id
join sys.tables t on t.object_id = tr.parent_id
To see all the default constraints, use the following query:
select
t.name as [TableName],
c.name as [ColumnName],
dc.[name] as [ConstraintName],
dc.[definition]
from sys.tables t
join sys.columns c on c.object_id = t.object_id
join sys.objects do on do.object_id = c.default_object_id
join sys.default_constraints dc on dc.object_id= do.object_id
If your insert statement is O.K., then the only reason would be a trigger that alters the value of the insert. (Providing there isn't a bug on your SQL Server. :-) )
So check if your table you're inserting into does have triggers and what they do.
To see the list of triggers either select from sys.triggers in the DB where is the table or in SQL Server Management Studio in the Object Explorer go to the table and then expand it / Triggers - then you can check each trigger. You need to check INSTEAD OF triggers. But you might have a look also onto AFTER triggers if INSTEAD OF triggers don't cause this.
The other option is that the insert statement has a bug and the column defaults to 1900. In that case, are you sure you insert into the column you want ? Do you use INSERT Table(List of columns) Values and the order of columns and order of values is correct ?
Related
I have the following query which is executed in a single string through C#.
SET #out_param := '';
SELECT
sightinguid
FROM
pc
INNER JOIN
c ON uid = id
WHERE
//... other conditions
AND (#out_param:=CONCAT_WS(',', sightinguid, #out_param))
LIMIT 50 FOR UPDATE;
UPDATE pc
SET
last_accessed_timestamp = NOW()
WHERE
sightinguid IN (#out_param);
SELECT #out_param;
I am basically trying to put the first 50 values of the first query in a comma separated string, and return this string at the end. Before doing so, I would like the update statement to execute on those same records. However, only the very first sightinguid is being updated. When I hardcode multiple values in the sightinguid IN (#out_param) part it works and updates them all - so I am assuming there is something wrong with that part.
I cannot put the SELECT in a subquery and update from there, due to the LIMIT 50 part, since MySQL does not let you put a LIMIT in a subquery.
Any ideas?
As you said, I don't know if you can use IN like that, i.e. using a variable.
Anyway, a simple workaround would be to use a temporary table to store information between the two queries:
CREATE TEMPORARY TABLE temp(
sightinguid #typeofsightinguid
)
INSERT INTO temp
SELECT //select1
sightinguid
FROM
pc
INNER JOIN
c ON uid = id
WHERE
//... other conditions
AND (#out_param:=CONCAT_WS(',', sightinguid, #out_param))
LIMIT 50 FOR UPDATE;
UPDATE pc
SET
last_accessed_timestamp = NOW()
WHERE
sightinguid IN (SELECT sightinguid FROM temp);
DROP TABLE temp;
SELECT #out_param;
If temporary tables are not an option (whatever the reason), then you're gonna have to do something like suggested here or here: basically, limit a subquery of the subquery. Like:
UPDATE pc
SET
last_accessed_timestamp = NOW()
WHERE
sightinguid IN (
SELECT sightinguid FROM (
SELECT //select2
sightinguid
FROM pc
INNER JOIN c
ON uid = id
WHERE //... other conditions
LIMIT 50
) tmp
)
Also, one more thing of note that I forgot to mention previously: using LIMIT without ORDER BY can result in non-deterministic queries, i.e. with different row order. So, following the example I wrote, you COULD get 2 different result sets on select1 and select2.
I have a stored procedure created in sql server 2008 wherein the columns from two different tables in the same database are displayed. I want to replace the NULL value in my column to blank. Can anyone help me in this?
AlTER PROCEDURE sp_Test123 --sp_Test123
AS
BEGIN
SELECT MediaContentType.MediaContentTypeID as ID,
MediaContentType.FileExtension,
IQCategory.Description,IQSubCategory.IQSubDesription
FROM MediaContentType
LEFT JOIN IQCategory
ON MediaContentType.MediaContentTypeID =IQCategory.IQCategoryID
LEFT JOIN IQSubCategory
ON MediaContentType.MediaContentTypeID = IQSubCategory.IQSubCategoryID
END
If you need to replace Null value in your query then it is very easy.
You have to use IsNull function.
Like
SELECT MediaContentType.MediaContentTypeID as ID,
ISNULL(MediaContentType.FileExtension,'') as FileExtension,
ISNULL(IQCategory.Description,'') as Description
ISNULL(IQSubCategory.IQSubDesription,'') as IQSubDesription
FROM MediaContentType
LEFT JOIN IQCategory
ON MediaContentType.MediaContentTypeID =IQCategory.IQCategoryID
LEFT JOIN IQSubCategory
ON MediaContentType.MediaContentTypeID = IQSubCategory.IQSubCategoryID
If you want to update the null value in your table then use update statement.
Like
Update MyTable
Set MyNullColumn = ''
where MyNullColumn Is Null
I am trying to code a simple database management tool in C#. I am in the process of coding a function to insert a new row into the database, but I have run into a problem. I need to be able to detect which ID numbers are not already taken. I have done some research but haven't found any clear answers.
Example table:
ID Name
---------------
1 John
2 Linda
4 Mark
5 Jessica
How would I add a function that automatically detects that ID 3 is empty, and places a new entry there?
Edit: My real question is; When I want to insert a new row via C#, how do I handle a column which is auto-increment? An example would be fantastic :)
I don't like giving answers like this...but I am going to anyway on this occasion.
Don't
What if you store more data in another table which has a foreign key to the ID in this table? If you reuse numbers you are asking for trouble with referential integrity down the line.
I assume your field is an int? If so, an auto increment should give more than enough for most purposes. It makes your insert simpler, and maintains integrity.
Edit: You might have a very good reason to do it, but I wanted to make the point in case somebody comes along and sees this later on who thinks it is a good idea.
SQL:
SELECT ID From TABLE
OR
SELECT t.ID
FROM ( SELECT number + 1 AS ID
FROM master.dbo.spt_values
WHERE Type = 'p'
AND number <= ( SELECT MAX(ID) - 1
FROM #Table
)
) t
LEFT JOIN #Table ON t.ID = [#Table].ID
WHERE [#Table].ID IS NULL
C#
DataTable dt = new DataTable();
//Populate Dt with SQL
var tableInts = dt.Rows.Cast<DataRow>().Select(row => row.Field<int>("ID")).ToList<int>();
var allInts = Enumerable.Range(1, tableInts.Max()).ToList();
var minInt = allInts.Except(tableInts).Min();
SELECT #temp.Id
FROM #temp
LEFT JOIN table1 ON #temp.Id = table1.Id
WHERE table1.Id IS NULL
Try this?
But my suggestion is, just autoincrement the field.
How you do that is, you set the IDENTITY property of the column to true, and set it as Primary key too(not null).
To handle inserts, you might need triggers, which are like stored procedures, but they can act in place of insert or update or delete, or before/after insert/update/delete
Google triggers.
from How do I find a "gap" in running counter with SQL?
select
MIN(ID)
from (
select
0 ID
union all
select
[YourIdColumn]+1
from
[YourTable]
where
--Filter the rest of your key--
) foo
left join
[YourTable]
on [YourIdColumn]=ID
and --Filter the rest of your key--
where
[YourIdColumn] is null
Good day,
I have a Time(DateTime) field in my SQL Server DB Table and I have to commit a record with a DateTime type on VS 2010 program to my DB. When I do I am getting the following error:
{"A column insert or update conflicts with a rule imposed by a previous CREATE RULE statement. The statement was terminated. The conflict occurred in database 'PTBODW', table 'dbo.MatchGPStoTripSchedule', column 'tTripScheduledStartTime'.\r\nThe statement has been terminated."} can anyone help me.
Thanks in advance.
Sounds like it may be a variable out of range. I'd fire up SQL profiler in SQL management studio and find the exact SQL that is causing the error. If its a bulk insert, I'd sucessively have the size of the insert until you isolat the (first?) row causing the issue.
Looks like the column is using the old sp_bindrule feature. You can list the rules in your database with:
select o.name as TableName
, c.name as ColumnName
, r.name as RuleName
from sys.objects o
join sys.columns c
on c.object_id = o.object_id
join sys.objects r
on r.object_id = c.rule_object_id
where o.is_ms_shipped <> 1
and rule_object_id <> 0
You can view the definition of a rule with sp_helptext:
exec sp_helptext 'RuleName'
Rules can be unbound from a column with sp_unbindrule (there can only be one rule per column, so sp_unbindrule does not need to know the rule's name):
exec sp_unbindrule 'MatchGPStoTripSchedule.tTripScheduledStartTime'
I am trying to insert a datetime stamp from an asp.net application into a db, but i keep recieving an error ::
The column "W_Date" cannot be modified
because it is either a computed column
or is the result of a UNION operator.
Can someone shed some light on this. Also, I automate the datetime in my asp in a label, then pull the text for the sql insert with the following code.
lblDate.Text = DateTime.Now.ToString();
Is this correct?
Below is my stored Proc code:
#date date
AS
BEGIN
INSERT INTO tbl_Wiki(W_Title, C_ID, W_Date)
VALUES (#title, #c_ID, GETDATE())
END
It doesn't sound like there's anything wrong with your ASP.NET code, assuming the W_Title is the correct column name. Do you have enough control over the schema to see if W_Title is a computed column or not?
Also, it looks like you're passing in "date" as a parameter to your proc, but you're not using it in the INSERT statement. If W_Date is a computed column to always be the current date, you should remove the W_Date paramter in your insert statement.
Check the definition of the column W_Date in table tbl_Wiki. It's probably a computed column, which means you can't modify it.
You could use this query to check if a column is computed:
select is_computed
from sys.columns
where object_id = object_id('tbl_Wiki')
and name = 'W_Date'
Example of a computed column:
create table Sample (a int, b int, c as sqrt(a*a+b+b))
Here, c is computed every time the row is retrieved. You can't overrule the calculation by specifying a value during an insert or update.