Database Question: Primary Key Cannot Be Null!
Jun 16, 2008
I am using SQL server. And, I have a database:
imgID int (primary key)
imgData image
imgTitle vchar
When I am going to perform insert command in my webpage, it pops out primary key cannot be null error!
Isn't primary key automatically generated? Or, where should I define it?
View 2 Replies
ADVERTISEMENT
Mar 30, 2008
Hi,
As I try to do an insert using an stored procdure I get an error reading...
"Cannot insert the value NULL into column 'cgpID', table 'AdminDB.dbo.CurrentGroup'; column does not allow nulls. INSERT fails."
What is wrong? cgpID is the primary key of the table CurrentGroup. It is the first field in the insert statement below and it is set to @@identity in the Values statement.
Thanks in advance!
ALTER PROCEDURE [dbo].[insert_currentgroup]
(
@cgpActivityGroupID nvarchar(30),
@cgpPreRegistredFrom nvarchar(30),
@cgpRegistredFrom nvarchar(30),
@cgpRegistredTo nvarchar(30),
@cgpMaximalNumber nvarchar(30),
@cgpStartDate nvarchar(40)
)
AS
SET Identity_insert [dbo].[CurrentGroup] ON
INSERT INTO dbo.CurrentGroup( cgpID, cgpActivityGroupID, cgpPreRegistredFrom, cgpRegistredFrom, cgpRegistredTo, cmrID, cgpMaximalNumber, cgpStartDate)
VALUES (@@identity, @cgpActivityGroupID, @cgpPreRegistredFrom, @cgpRegistredFrom, @cgpRegistredTo, 1, @cgpMaximalNumber, @cgpStartDate)
SET Identity_insert [dbo].[CurrentGroup] OFF
View 2 Replies
View Related
Sep 15, 2004
Friends,
I am inserting a value from vb.net to sql server 7.
i created a table in the sqlserver with primary key.
In VB.net form i didnt check the values of the check box.
when i try to save the empty or null the sql server should throw the error. but its accepting the null value.
how is it possible?
can anyone help me?
FYI:
table name: JobMast
Fields:
jobcode int primary key
jobtitle varchar(10)
View 12 Replies
View Related
Jul 23, 2005
I have a case where a table has two candidate primary keys,but either (but not both) may be NULL. I don't want to storea copy of the concatenated ISNULL'ed fields as an additionalcolumn, though that would work if necessary. Instead, I triedthe following (this is a related simplified example, not myreal one):CREATE FUNCTION ApplyActionPK(@IP int = NULL,@DNS varchar(64) = NULL)RETURNS varchar(74) -- NOT NULLASBEGINdeclare @val varchar(74)set @val = str(ISNULL(@IP, 0), 10)set @val = @val + ISNULL(@DNS, '')return @val-- Also tried "return str(ISNULL(@IP, 0), 10)+ISNULL(@DNS, '')"-- Also tried "return ISNULL(STR(@IP, 10), ISNULL(@DNS, ''))"-- ... and other things...ENDGOcreate table ApplyAction(-- An action applies to a computerAct varchar(16) NOT NULL,-- The action to applyIP int NULL,-- The computer IP address, orDNS varchar(64) NULL,-- The DNS name of the computerTarget as dbo.ApplyActionPK(ComputerID, DNS), -- PK value-- Also tried "Target as ISNULL(STR(@IP, 10), ISNULL(@DNS, ''))"CONSTRAINT PK_ApplyAction PRIMARY KEY(Act, Target))SQL Server always complains that the primary key constraint cannot becreated over a nullable field - even though in no case will the 'Target'field be NULL.Please don't explain that I should store an IP address as a string.Though that would suffice for this example, it doesn't solve myactual problem (where there are four nullable fields, two of whichare FKs into other tables).What's the reason for SQL Server deciding that the value is NULLable?What's the usual way of handling such alternate PKs?Clifford Heath.
View 7 Replies
View Related
Oct 24, 2006
In a new instalation of SQL Server 2005. I've made a restore from SQL Server 2000 database.
Solve some problem with the user, and it looks ok.
I'm using a asp web aplication, with vb dll, and change the sql provider from "SQL Server" to "SQL Native Client". It works, but in some recordsets the value a recive for the table primary key is null?????
If execute the querie in the database, the result has values in the primary key.
the same appends when i connect to an SQL Server 2000 using "SQL Native Client".
Please help, what can i do.
View 7 Replies
View Related
Jul 18, 2015
Using TSQL, I have a table that holds filenames of Pictures for products. Different products can be using the same picture. I need to select the filenames for a single product only if it does not exists for a different product.I have tried Where Exists (select FileName From Tbl where
Prod_Id = @var) AND NOT EXISTS(select FileName From Tbl where
Prod_Id != @var) In the Select Statement.Â
View 6 Replies
View Related
Jan 20, 2004
Cannot find an answer to this in previous posting, though there are similar topics.
My primary key "ID" requires a value (is not nullable), and not explictly providing it with one when I update a new record gives the following error:
Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'ID', table 'AdClub.mediaq.News'; column does not allow nulls. INSERT fails.
However, trying to stuff that field with a recordCount+1 value (or any value), I get this error:
Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'Primary Key'. Cannot insert duplicate key in object 'News'.
Cannot figure this one out. The value I'm providing for that field is known to be unique, but the SQL Server spits it out each time.
Is there a way to have the ID primary field automatically update with a new value when a new record is generated? This is how I used to do it in Access, but cannot find a similar feature in SQL Server. I'm sure I'm missing something simple, but right now I'm stuck in this "Catch-22" situation.
Please help!
View 5 Replies
View Related
Jun 28, 2004
I would drop and add the table but the data can't be deleted. So if anyone could help with the statement it would be greatly appreciated. Thanks
View 7 Replies
View Related
Oct 27, 2015
We have a case where in we should show date based on conditions for e.g if we had a column defined as
col varchar(10) then we would show col as 'NULL' for some condition and actual value when no condition
Normaly date values are stored here e.g under col 20150901 .
CaseÂ
when col>'20150901' then 'NULL'
else col
end as Derivedcol
Note this is an extract process and we are presenting data by pumping the data in a table .
Now there is another similar column -colz varchar(10) Â which stores date but doesnt have case condition so whenever date has no value its shows null which is database null.
So whats the difference between database null and string null ?
 How can we show database null for the case condition instead of string "null"?
View 10 Replies
View Related
Sep 30, 2014
We have a database where many tables have a field that has to be lengthened. In some cases this is a primary key or part of a primary key. The table in question is:-
/****** Object: Table [dbo].[DTb_HWSQueueMonthEnd] Script Date: 09/25/2014 14:05:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[DTb_HWSQueueMonthEnd](
[Code] ....
The script I am using is
DECLARE@Column varchar(100)--The name of the column to change
DECLARE@size varchar(5)--The new size of the column
DECLARE @TSQL varchar(255)--Contains the code to be executed
DECLARE @Object varchar(50)--Holds the name of the table
DECLARE @dropc varchar(255)-- Drop constraint script
[Code] ....
When I the the script I get the error message Could not create constraint. See previous errors.
Looking at the strings I build
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] DROP CONSTRAINT PK_DTb_HWSQueueMonthEnd
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] Alter Column [Patient System Number] varchar(10)
ALTER TABLE [dbo].[DTb_HWSQueueMonthEnd] ADD CONSTRAINT PK_DTb_HWSQueueMonthEnd PRIMARY KEY NONCLUSTERED ([Patient System Number] ASC,[Episode Number] ASC,[CensusDate] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
They all seem fine except the last one which returns the error
Msg 8111, Level 16, State 1, Line 1
Cannot define PRIMARY KEY constraint on nullable column in table 'DTb_HWSQueueMonthEnd'.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
None of the fields I try to create the key on are nullable.
View 2 Replies
View Related
Nov 5, 2007
Hi all,
I downloaded and ran AdventureWorks.msi into my SQL Server Management Studio Express (SSMSE) one year ago.But I did not know how to attach it to my SSMSE then. Last week, I deleted it from the "Add or Remove" of Control Panel and I downloaded the new AdventureWork.msi and installed it my SSMSE. Today, I tried to use the Database Explorer of VB 2005 Express for the first Stored Procedure programming. I clicked on AdventureWorks.mdf and I got the following error: One or more files do not match the primary of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupt and should be restored from a backup. Cannot open user default database. Login failed. Login failed for user 'CENADe1enxshc'. Log file 'C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataAdventureWorks_Data_log.ldf' does not match the primary file. It may be from a different database of the log may have been rebuilt previously. Please help and advise me how to correct this problem.
Thanks,
Scott Chang
View 9 Replies
View Related
Jan 17, 2008
Hi, I have a Users table that I use for membership. Now I am using username varchar(30) as the primary key for this table since username will always be unique.I am storing username in UsersInRole table so that I can find what roles each user has.The question I have is regarding how SQL Server actually stores data:I see that when I add users, they are always stored alphabetically sorted on username. I was expecting that all users will appear on the users table in the order they were added.Example: I have 3 users (john, jonah, wilson). Now I added 4 user with username='bob'If I execute select * from users, it returns me (bob, john, jonah, wilson). Look bob is has become the first row of the table.My question: Is Sql server moving 3 older rows to make room for 'bob' and it is also rebuilding part of the index due this new username 'bob'?If this is the case, then it will have big impact if I have 100K users and I add one user that becomes firstrow. In that case huge other rows will have to move.Bottom line, insert, delete will be expensive. I know sql server keeps data physically sorted on PK. But I am concerned here since rows are losing the order in which they were inserted.Thanks
View 8 Replies
View Related
Jun 11, 2014
I would like to do partitioning one of my client, but that primary database is participating in log shipping.
If I do partitioning on primary, automatically apply those changes on secondary db? if not, what is the way?
Note: I am adding new filegroups and ndf file in different drives on primary database.
View 2 Replies
View Related
Sep 20, 2006
Hey. I need to substitute a value from a table if the input var is null. This is fine if the value coming from table is not null. But, it the table value is also null, it doesn't work. The problem I'm getting is in the isnull line which is in Dark green color because @inFileVersion is set to null explicitly and when the isnull function evaluates, value returned from DR.FileVersion is also null which is correct. I want the null=null to return true which is why i set ansi_nulls off. But it doesn't return anything. And the select statement should return something but in my case it returns null. If I comment the isnull statements in the where clause, everything works fine. Please tell me what am I doing wrong. Is it possible to do this without setting the ansi_nulls to off??? Thank you
set ansi_nulls off
go
declare
@inFileName VARCHAR (100),
@inFileSize INT,
@Id int,
@inlanguageid INT,
@inFileVersion VARCHAR (100),
@ExeState int
set @inFileName = 'A0006337.EXE'
set @inFileSize = 28796
set @Id= 1
set @inlanguageid =null
set @inFileVersion =NULL
set @ExeState =0
select Dr.StateID from table1 dR
where
DR.[FileName] = @inFileName
AND DR.FileSize =@inFileSize
AND DR.FileVersion = isnull(@inFileVersion,DR.FileVersion)
AND DR.languageid = isnull(@inlanguageid,null)
AND DR.[ID]= @ID
)
go
set ansi_nulls on
View 3 Replies
View Related
May 23, 2006
Doing the exercises in a book, which starts CREATE DATABASE xyz ON PRIMARY...
It fails, so stepping through it. What is PRIMARY?
Searching Help seems always to give primary KEY, but cannot be that at point of creating the DB.
XP ProVS Pro 2005SQL Server 2005 Dev.
View 2 Replies
View Related
Aug 7, 2000
Hi,
Can anyone tell me a solution how to combine 3 primary files that are existing in a particular database into one. One of the database that was running has three primary(.mdf) files. Can any one tell me whether the files created in that way has impact on the performance of the server.Solution for this problem is highly appreciated. Thanks in advance.
VS.
View 1 Replies
View Related
Jul 31, 2006
I have a table that was set up with a primary key - that i need to change. The problem is that the database is being replicated to a remote location, and will not allow me to remove or change the primary key on a published database.
Due to the size of the database and bandwith limitations it is not an option to re-initialise the published database.
Is there any to do this without breaking replication
View 1 Replies
View Related
May 6, 2015
We are doing restoring in a different data center and keep sending log backups and restore from there.Recently we want to bring a new volume to the sql server and move all databases to the new volume, then the problem comes, I did a test that I cannot simply change the drive letter, i.e. old disk letter x, new disk letter y, then I turn off all sql instances and move all databases(restoring status) to disk y, then get rid off disk x, resign x to disk y, so now new disk has old letter x now. then I continue the restore log against latest log backup, it returns the error.
Msg 3446, Level 16, State 2, Line 4
Primary log file is not available for database 'TestDB' (7:0). Â The log cannot be backed up.
Msg 3013, Level 16, State 1, Line 4
RESTORE LOG is terminating abnormally.
Is there a way to do this? or SQL Server doesn't support this change.
View 9 Replies
View Related
Sep 7, 2006
hii I have to insert some data into a table from the webpage. For that I need to know the last occurred value in the primary key and increment this by one and then insert the new record into the table. I am working with SQL Server 2005. I am coding in VB and ASP.NET 2.0. How will I go about this?? Is there some easy way for me to knw the last value of the primary key n then insert the record. It would be great if I get the idea more clear with the help of some code... Thanks
View 2 Replies
View Related
Oct 25, 2007
Update: Changed original post as I figured it was not the problem I stated.
Hi all,
Heres the problem. I have a table in SQL Server with two fields, PartSubCategory and PartCatID. PartSubCategory is the primary key. When I import an excel sheet with identical columns into this table, the primary key column in the table gets sorted automatically (alphabetically). I don't want this column sorted but to import the rows from excel in the order as they were. Is this some indexing issue? Is there a fix?
Thanks a lot...Bullpit
View 13 Replies
View Related
May 12, 2008
I'm working with a legacy database whose structure I cannot change. I'm building a web-based editor for one of the DB's tables. This table has a Primary Key called "Master_Idx" that is an Identity (autonumber) field.To start, I query the DB and populate a data table which is cached. This is used to "feed" the web form. Any additions, changes, and deletions are reflected in this cached table.The user then has the flexibility to press Save at any time, which ensures that the database is modified accordingly.Here's my question:When new records are added, I assign them a Master_Idx value, the first of which was calculated to be 1 + the Max(Master_Idx) value when the editing session started. But when I insert these records back into the database it's possible that another user might have also been doing similar editing (of different records from the same table), so there's no guarantee that the Master_Idx values in the data table will be identical to those in the DB. When I insert a record from the cached table back into the DB, what technique can I use to check what value was assigned to the Master_Idx? If it's not the same as in the cached table then I need to update it locally in a few places.I hope all of this makes sense but if it doesn't then let me know and I'll explain it in another way.Robert W.
View 2 Replies
View Related
Apr 5, 2005
Hi!
I have seen two approaches to primary keys. First one - and it is like
default - is to use surrogate key as primary key. For each table I will
create some autonumeric field hat cannot be changed once it has value.
Some materials refer to this key also as technical primary key. I
design my databases this way usually.
The other approach is to create primary key of fields that make primary
key on database logical model. This approach is not so popular and has
some side effects like a little bit clumpsy looking joins and
unconvenient use in applications.
Question: What is the main idea behind second approach? Or how explain their preference database designers who are using second approach?
View 6 Replies
View Related
Jul 26, 2003
Hi all,
1) a company is maintaining seperate Database(s) for each country
2) Invites the user regn from diff. country
3) How to check the Primary key constraint for each user user regn accross all the country databases Dynamically when registering.
4)ie. all users of that company, all over the world are given a unique ID.
5) How to ensure this in MS SQl SERVER 2000,or Oracle
pls HElp
Thanks in adv.
Tarriq
View 2 Replies
View Related
Apr 30, 2014
choosing a primary key for the database which i am designing.
I have few tables which contains 5 -15 fields out of it 3 - 9 columns combined to form the uniqueness of the row.
All are un-related tables. Three parent tables connect with 20 child non-related child tables.
I believe it would not be a wise choice to choose 3 to 9 fields for primary key. But if i use an auto increment as a key will there be of any use as it might never be used to fetch rows. Then why do i still have to go with that?
Or Is it ok to create a primary key of upto 5 attributes?
View 9 Replies
View Related
Mar 1, 2015
In always on docs in msdn they mention only about backup of secondary.. explain the backup of primary or how logs are managed in primary database. My doubt is a normal database in full recovery mode the log file will grow if we didnt take proper log backup,how the same is managed in primary in Always On.
View 2 Replies
View Related
Aug 6, 2007
I really needed to move the tempdb file to another hard drive, so I used this bit of code.
USE master
go
ALTER DATABASE tempdb MODIFY FILE (NAME = tempdev, FILENAME = 'E: empdb.mdf')
go
ALTER DATABASE tempdb MODIFY FILE (NAME = templog, FILENAME = 'E: emplog.ldf')
go
Now sql server manager won't even start. The log files says
"tempdb.mdf is not a privary database file. CREATE DATABASE failed. Some file names listed could not be created.
WARNING: problem activiating all tempdb files. See previous errors."
Any ideas on how to make this program work again, without reinstalling it?
View 3 Replies
View Related
Aug 8, 2007
Hi Everone,
I need help on how to produce a SQL Server Database Primary Data File, i have read the Visual C# 2006 book by Deitel and Deitel unfortunately the book does not say how to produce the forementioned data file. The software that i currently have to help me produce this data file is Visual C#, J#, Web Development, SQL Server 2005 and Office 2007.
I have a good understanding of databases from studying SQL and Oracle but i am not sure which is the best software to use to produce the Primary Data File, ideally i would like to use Access from my Office 2007 package.
Many thanks for your help in resolving this problem.
View 4 Replies
View Related
Jun 14, 2006
Hi,
If I perform a point in time restore on a database that is currently a primary log shipping database, will the rollback be reflected on the secondary servers or are extra steps neccesary to accomplish this?
Thanks.
View 1 Replies
View Related
Apr 17, 2014
how to find all primary key columns & foreign key columns in all database tables?
View 1 Replies
View Related
Feb 12, 2007
Hello guys
My server crashed but luckily I was not able to get back my files with help of recovery software.
Now, all I have from the database are just sql server database primary data .mdf and sql server databaseTransaction Log Files .ldf. I need to restore these data back to sql server.
Please could someone tell me how to restore these two file types back to my sql sever 2007 database?
Thanks
netboy
View 3 Replies
View Related
May 18, 2006
I am considering not to allow null values in the database.
what are pros and cons ?
View 3 Replies
View Related
Apr 29, 2008
I've just applied CU7 to a set of SQL2005 SP2 servers with no problems, except on one server.
I've now fixed the problem, but couldn't find description of it elsewhere so post it here in case it helps anyone else with the same problem.
Here's the problem I had. The server is Windows 2003 with two instances of SQL 2005 SP2 (9.00.3186)
1) Ran the patch (SQLServer2005-KB949095-x86-ENU.exe)
2) C: drive ran out of space whilst patch was running against instance A
3) Cleared down space on C: drive
4) Patch had hung, after 45 minutes of no activity I killed it
5) Re-ran patch, it reported instance A as upgraded already and just upgraded instance B
6) After reboot instance A failed to start. Instance B started with no problem.
The service was failing to start with the following recorded in the log:
Server Microsoft SQL Server 2005 - 9.00.3239.00 (Intel X86)
[€¦]
spid5s The resource database build version is 9.00.3186. This is an informational message only. No user action is required.
spid5s Error: 5173, Severity: 16, State: 1.
spid5s One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupted and should be restored from a backup.
spid5s Error: 5173, Severity: 16, State: 1.
spid5s One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupted and should be restored from a backup.
spid5s Log file 'C:Program FilesMicrosoft SQL ServerMSSQL.2MSSQLDATAmssqlsystemresource.ldf' does not match the primary file. It may be from a different database or the log may have been rebuilt previously.
spid5s The log cannot be rebuilt when the primary file is read-only.
spid5s Error: 945, Severity: 14, State: 2.
spid5s Database 'mssqlsystemresource' cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server errorlog for details.
I think that the patch must have got part-way through instance A, enough to mark it as being patched, but not far enough to patch the mssqlsystemresource system database (note the version numbers in the log above - 9.00.3239 vs 9.00.3186).
The hotfix log records an error opening the registry, but the detailed log was overwritten by the subsequent (successful) run of the hotfix so there€™s no more detail available.
To fix this I copied in the mssqlsystemresource mdf and ldf files from instance B (which wasn€™t patched the first time round, and was subsequently patched successfully). From what I understand mssqlsystemresource is read-only and holds copies of system sprocs etc, so a copy will suffice. Plus I am assuming the SQL Server is clever enough to complain if it€™s not happy with the instance of the file.
Note that the problem recorded elsewhere for this error, where mssqlsystemresource or other system DBs have been moved from their original installation folders, was not the cause here.
Not sure if this is the 'correct' fix, but it got Instance A up and running. Obviously YMMV
View 2 Replies
View Related
May 31, 2007
In my database, in a few tables there are NULL values in some of the columns. This is okay, but I need to know how to query for nulls. For example I tried the following query but it did not work:
select * from Employee where DateOfBirth =NULL
This did not work so I also tried the following:
select * from Employee where DateOfBirth ='NULL'
Neither of these worked. Can someone help me out?
View 1 Replies
View Related