There is a scenario where I have to drop primary key on a existing table and then insert a record into it. The table has a column called GUID as shown below
Create Table TEST_TABLE_VALUE (
TEST_TABLE_ID int Identity(1,1),
TEST_TABLE_VALUE int,
GUID uniqueidentifier Not Null Default newid(),
Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE)
)
Dropped the constraints using below code
Declare #TableName nvarchar(100)
Declare #TableId int
Declare #ConstraintName varchar(120)
Declare #IndexName varchar(120)
Declare #Command varchar(256)
Set #TableName = 'TEST_TABLE_VALUE'
Select #TableId = id From sysobjects Where [type]='U' and [name]=#TableName
Declare ConstraintDropCursor Cursor Local Fast_Forward
For Select name from sysobjects where (type='K' Or type='D' or type='F' or type='C') and parent_obj = #TableId
For Read Only
Open ConstraintDropCursor
Fetch Next From ConstraintDropCursor Into #ConstraintName
While ##Fetch_Status != -1
Begin
Set #Command = 'Alter Table dbo.' + #TableName + ' Drop Constraint ' + #ConstraintName
exec(#Command)
Fetch Next From ConstraintDropCursor Into #ConstraintName
End
Close ConstraintDropCursor
DeAllocate ConstraintDropCursor
After dropping the constraints when I tried to insert data into the table
Insert Into TEST_TABLE_VALUE (TEST_TABLE_VALUE) Values(1)
but got the below error:
Cannot insert the value NULL into column 'GUID', table 'CustApp1.dbo.TEST_TABLE_VALUE1'; column does not allow nulls. INSERT fails.
How can I solve this issue?
You have dropped the default for GUID column and it is not nullable column.Thus it is causing the issue. In case you want to insert lots of data and do not want constraint for maybe perf reasons. Then atleast do not drop the defaults for not nullable columns.
Well if you drop the default constraint you end up with
Create Table TEST_TABLE_VALUE (
TEST_TABLE_ID int Identity(1,1),
TEST_TABLE_VALUE int,
GUID uniqueidentifier Not Null,
Primary Key (TEST_TABLE_ID, TEST_TABLE_VALUE)
)
so if you wish to continue down this path you either have to provide a value for the GUID column
or also do
ALTER TABLE TEST_TABLE_VALUE ALTER COLUMN GUID uniqueidentifier NULL
to allow nulls.
Related
I have a Transaction Inventory table that contains (TIID, TID, catid, itemid, quantity, price, isdelete, entryNumber) Columns. I inserted Tow record's and the TID is default null. When I execute update stored procedure I want to update all TID null column with id that i have where TIID IN(#TIID).
Table after record's inserted
Stored Procedure
ALTER procedure [dbo].[UpdateTIID]
#TIID nvarchar(max),
#TID nvarchar(50)
as
begin
declare #sql nvarchar(max)
set #sql='Update TransactionInventory Set TID='+ #TID +'
where TIID IN ('+ #TIID +') '
print #sql
exec (#sql)
end
C# Code
I have a table like the below picture, and I want to get IDwithChar column value concatenating the value with image address, and inserting that into ImageCover column at same query, how can I achieve that ?
Try to concate the two column values and Use UPDATE statement to update the value in the related column.
CREATE TABLE Test (
IdWithChar NVARCHAR(MAX),
ImageAddress NVARCHAR(MAX),
CoverImage NVARCHAR(MAX)
)
INSERT INTO Test VALUES ('B00001','Test Address','Test-Image-Url')
Query:
UPDATE TEST
SET CoverImage= IdWithChar +' '+ ImageAddress
WHERE Your_condition
first you must insert values and get the last identity and then update the field in the record.
insert into item values ('test', 'test')
declare #itemId int = ##IDENTITY
update item set item_code = #itemId where item_id = #itemId
I have created a user defined type (with script to CREATE) given below:
CREATE TABLE [dbo].[EmployeeMasters](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EmployeeID] [varchar](max) NOT NULL,
[EmployeeFName] [varchar](max) NOT NULL,
[EmployeeLName] [varchar](max) NOT NULL,
[Photo] [image] NOT NULL)
On the same database I have created a procedure that uses this type:
create PROCEDURE EmpQuli_INSERT #EmployeeID varchar(Max),#EmployeeFName VARCHAR(MAX), #EmployeeLName VARCHAR(MAX),#Photo IMAGE AS BEGIN DECLARE #NEWID VARCHAR(10);
DECLARE #PREFIX VARCHAR(MAX);
SET #PREFIX = UPPER(SUBSTRING('STR',1, 3)) SELECT #NEWID = (#PREFIX + replicate('0', 3 -len(CONVERT(VARCHAR,N.OID + 1))) + CONVERT(VARCHAR,N.OID + 1)) FROM (SELECT CASE WHEN MAX(T.TID) IS null then 0 else MAX(T.TID) end as OID FROM (SELECT SUBSTRING(EmployeeID, 3, 1) as PRE_FIX,SUBSTRING(EmployeeID, 3, LEN(EmployeeID))as TID FROM EmployeeMasters) AS T WHERE T.PRE_FIX = #PREFIX) AS N
insert into EmployeeMasters values(#NEWID,#EmployeeFName, #EmployeeLName, #Photo);
end
And I try to insert a value in c# I getting operand type clash : image is incomplate with varchar(max) in sql server
The c# code is:
EmployeeFName.Value = textBox_emp_Fname.Text;
EmployeeLName.Value = textBox_emp_Lname.Text;
Photo.Value =img_arr1;
AddEmployee.CommandText = "EmpQuli_INSERT #EmployeeFName, #EmployeeLName, #Photo";
I don't know who to fix it. Please help me because I have to submit my final year project on June first week but now I struggle this exception please help....
You're missing a column in your insert statement:
insert into EmployeeMasters values(#NEWID,#EmployeeFName, #EmployeeLName, #Photo);
EmployeeID is missing, so #Photo tries to save into #EmployeeLName, which is incompatible. Even if it weren't, you'd still be missing EmployeeID, which is NOT NULL.
I'd suggest using the explicit insert syntax instead of relying on the auto-supplied columns:
insert into EmployeeMasters(EmployeeID, EmployeeFName, EmployeeLName, Photo)
values (#NewID, #EmployeeFName, #EmployeeLName, #Photo);
I'm using WPF MVVM Pettern and
I Have a simple table on SQL Server 2012 which its ID(key) column is computed in an StoredProcedure, called PersonInsert: (This is simplified, but what is computed is more complex than this, anyway it's an int at last)
USE [Guard]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[PersonInsert]
#FName NVARCHAR(50) ,
#LName NVARCHAR(50) ,
#ID INT = NULL OUTPUT
AS
BEGIN
BEGIN TRY
SELECT #ID = ISNULL(MAX(ID), 0) + 1
FROM dbo.Person
INSERT INTO [dbo].[Person]
( [ID] ,
[FName] ,
[LName]
)
VALUES ( #ID ,
#FName ,
#LName
)
END TRY
BEGIN CATCH
DECLARE #ErrMsg NVARCHAR(MAX) ,
#ErrSvr INT ,
#ErrStt INT
SELECT #ErrMsg = ERROR_MESSAGE() + '|' + ERROR_PROCEDURE() + '|'
+ CAST(ERROR_LINE() AS NVARCHAR(5)) ,
#ErrSvr = ERROR_SEVERITY() ,
#ErrStt = ERROR_STATE()
RAISERROR (#ErrMsg, #ErrSvr, #ErrStt)
END CATCH
END
GO
In the .net side, I use EF 6.1 Code-First to handle data and mapped to SPs so I have OnModelCreating like this:
modelBuilder.Entity(Of Person)().MapToStoredProcedures(
Sub(x)
x.Insert(Function(e) e.HasName("[dbo].[PersonInsert]"))
x.Update(Function(e) e.HasName("[dbo].[PersonUpdate]"))
x.Delete(Function(e) e.HasName("[dbo].[PersonDelete]"))
End Sub)
And My Model is:
<Table("Person")> _
Partial Public Class Person
<DatabaseGenerated(DatabaseGeneratedOption.None), Key> _
Public Property ID As Integer
Public Property FName As String
Public Property LName as String
End Class
Now the strange thing is, when I try to Insert Data (Adding New Person) at first time, the db.SaveChanged() works great, but for second time it throws InvalidOperation exception with a message:
The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Saving or accepting changes failed because more than one entity of type 'Shoniz.Guard.WPFGuardApplication.Person' have the same primary key value. Ensure that explicitly set primary key values are unique. Ensure that database-generated primary keys are configured correctly in the database and in the Entity Framework model. Use the Entity Designer for Database First/Model First configuration. Use the 'HasDatabaseGeneratedOption" fluent API or 'DatabaseGeneratedAttribute' for Code First configuration.
He is right! the data is comitted successfully! and I'm right too, because my ID(key) column is computed right and it's completely unique. Either I have used the DatabaseGeneratedAttribute with none value on ID, but the result is the same :(
Even when I re-query the db to check about duplicate keys, I find NOTHING!
Why this exception is thrown?
How can I prevent that?
Is there anyway to Ignore the changes after db.SaveChanges()?
First of all change DatabaseGeneratedOption.None to DatabaseGeneratedOption.Indetity
and finally change stored procedure to this:
BEGIN TRY
SELECT #ID = ISNULL(MAX(ID), 0) + 1
FROM dbo.Person
INSERT INTO [dbo].[Person]
( [ID] ,
[FName] ,
[LName]
)
VALUES ( #ID ,
#FName ,
#LName
)
--You have to tell EF this is returned Id of inserted person
SELECT #ID as ID
END TRY
I have one login form like :
Username: Ashish
Password: Pass
Contact no: 1234567890
State: Maharashtra
Having two tables :
create table DGRegion
(DG_Regionno Int Identity (1,1) NOT Null constraint pk1 Primary Key,
DG_Username varchar(50),
DG_Password varchar(50),
DG_Contactno int ,
DG_StateNo int References DGState(DG_stateno))
Create table DGState
(DG_stateno Int Identity (1,1) NOT Null constraint pk Primary Key ,
DG_State varchar (50))
Now how can I create one stored procedure P which will enter values into DGRegion and DGState tables?
After click on submit I'm using asp.net.
Problem is: I can enter values into DGRegion table directly but how can I enter reference of state into table DGState?
Try something like this:
CREATE PROCEDURE dbo.EnterLoginData(#Username VARCHAR(50), #Password VARCHAR(50),
#ContactNo INT, #StateName VARCHAR(50))
AS BEGIN
DECLARE #StateID INT
-- check if state already exists
IF EXISTS(SELECT * FROM dbo.DGState WHERE DG_State = #StateName)
-- if it exists - retrieve the DG_StateNo
SELECT #StateID = DG_StateNo
FROM dbo.DGState
WHERE DG_State = #StateName
ELSE BEGIN
-- if it doesn't exists - insert new row
INSERT INTO dbo.DG_State(DG_State) VALUES(#StateName);
-- get the newly inserted row's ID using SCOPE_IDENTITY()
SELECT #StateID = SCOPE_IDENTITY()
END
INSERT INTO
dbo.DGRegion(DG_Username, DG_Password, DG_ContactID, DG_StateNo)
VALUES(#Username, #Password, #ContactNo, #StateID)
END
In the sp:
check if the state is in the state table
if not, put it into the state table
get the id (DG_stateno) of the state table, put in variable
execute your insert