How to use identity column value of target table to insert in another column of same table - sql

Pardon the title of question if it is confusing. Table E is source and Table S is target. S.SEA_ID is identity column (int, not null). Whenever those join conditions are NOT MATCHED AND E.ACCT_NUM IS NULL, I want to insert the value 'EY|' + CAST(S.SEA_ID AS VARCHAR) in column S.ACCT_NUM. But I am getting the error
The multi-part identifier "S.SEA_ID" could not be bound.
Is it possible to insert identity column value of target table to populate another column of the same target table? If it is not possible in below MERGE statement, what are my other options?
MERGE INTO STG_EXTERNAL_ACCT S
USING ##EYDUPLICATES E
ON E.COUNTERPARTY_NAME = S.COUNTERPARTY_NAME
AND E.COUNTERPARTY_ADDRESS = S.COUNTERPARTY_ADDRESS
AND E.COUNTERPARTY_STATE = S.COUNTERPARTY_STATE
AND E.COUNTERPARTY_COUNTRY = S.COUNTERPARTY_COUNTRY
AND E.COUNTERPARTY_CITY = S.COUNTERPARTY_CITY
WHEN NOT MATCHED AND ISNULL(E.ACCT_NUM,'')=''
THEN INSERT (ACCT_NUM, COUNTERPARTY_NAME, COUNTERPARTY_ADDRESS,
COUNTERPARTY_STATE, COUNTERPARTY_COUNTRY, COUNTERPARTY_CITY)
VALUES ('EY|' + CAST(S.SEA_ID AS VARCHAR),E.COUNTERPARTY_NAME,
E.COUNTERPARTY_ADDRESS, E.COUNTERPARTY_STATE,
E.COUNTERPARTY_COUNTRY, E.COUNTERPARTY_CITY);

I suggest that change ACCT_NUM Column as calculated column.
ALTER Table STG_EXTERNAL_ACCT ALTER Column ACCT_NUM as 'EY|'+CAST(S.SEA_ID AS VARCHAR)
Also you can set this column in trigger.
Create Trigger TiggerName ON STG_EXTERNAL_ACCT
INSTEAD OF INSERT
AS Begin
Insert Into STG_EXTERNAL_ACCT (ACCT_Num, ...)
Select 'EY|'+CAST(S.SEA_ID AS VARCHAR), ...
From Inserted
End

Related

Not able to insert a row in a table which has auto incremented primary key

I have a table reportFilters which has the following column names:
The reportFilterId is auto increment. I want to insert a row in the table with the script below:
IF OBJECT_ID(N'ReportFilters', N'U') IS NOT NULL
BEGIN
IF NOT EXISTS (SELECT * FROM [ReportFilters]
WHERE ReportId IN (SELECT ReportId FROM [Reports] WHERE ReportType = 'Operational Insights Command Staff Dashboard') )
BEGIN
INSERT INTO [ReportFilters] Values(1, 'SelectView', 'Select Views', 13, 'Views','Views', 'SelectView', 'a', 'b', 'c' );
END
END
GO
But I am getting the following error:
Column name or number of supplied values does not match table definition.
Can I please get help on this ? Thanks in advance.
I think the problem is on inserted columns can't match with inserted data because that will instead by your table column order which is ReportFilterId instead of ReportId
So that there are 11 columns in your table but your statement only provides 10 columns.
I would use explicitly specify for inserted columns (inserted columns start from ReportId except your PK ReportFilterId column)
INSERT INTO [ReportFilters] (ReportId,ReportFilterName,ReportFilterTitle....)
Values (1, 'SelectView', 'Select Views', 13, 'Views','Views', 'SelectView', 'a', 'b', 'c' );

How to Update a column which is created by using cast - identity

Is there any way to update column which is created with cast
CREATE TABLE test
(
num INT IDENTITY(1, 1),
Token AS 'TK_' + CAST(num VARCHAR(10)),
name VARCHAR(100)
)
INSERT INTO test VALUES ('data')
If I execute the above query, my result for token column will be "tk_1".
Is it possible to update/insert manually for that "token" column value?
Computed columns are read-only and IDENTITY values cannot be updated. With the computed column, all you can do is indirectly control the value during inserts using IDENTITY_INSERT but that defeats the purpose of using IDENTITY.
If you want to update the value after inserted, make it a regular varchar(13) column and assign the initial value in an insert trigger. That would allow you to update the value to something else after the initial insert.

Confusion about Stored Procedure

I have written a stored procedure for inserting data into my table. These are my table's columns with their datatype:
Ad nvarchar(150),
Yazar nvarchar(150),
SayfaSayisi smallint,
KategoriId int
Gmc datetime,
HostName nvarchar(150)
The problem is that Gmc and HostName have their own default values. So I can't use these two in the stored procedure.
Gmc ---> GetDate() (to get insert date)
HostName --> Host_Name( )
So when I execute the query I am getting this error.
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement
This is the query
Create proc Kitap_Insert
#Ad nvarchar(150),
#Yazar nvarchar(150),
#SayfaSayisi smallint,
#KategoriId int
Gmc datetime,
HostName nvarchar(150)
as
Insert into Kitap(Id, Ad, Yazar, SayfaSayisi, KategoriId)
values(#Ad, #Yazar, #SayfaSayisi, #KategoriId)
What is the proper way of doing this?
You need remove ID from insert list
Insert into Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
values(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
or add a value for it as below
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(#ID, #Ad,#Yazar,#SayfaSayisi,#KategoriId)
Instead of :
Insert into Kitap(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
Use:
INSERT INTO Kitap(Ad,Yazar,SayfaSayisi,KategoriId)
VALUES (#Ad,#Yazar,#SayfaSayisi,#KategoriId)
You are asking SQL engine that you will provide id (an additional field) as well (field that doesn't exist in the table or is an auto increment field) and you are not providing the value for the same and hence your error here are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement
So remove additional Id from your insert query.
The error you are getting because you tried to insert value into more column names than specified in Values Clause.
If you have ID column as Auto-increment field in table so you dont have to include that ID column in so your insert query will be like this:-
Insert into Kitap
(Ad,Yazar,SayfaSayisi,KategoriId)
values
(#Ad,#Yazar,#SayfaSayisi,#KategoriId)
If you don't have ID column as Auto-increment field in table so you provide value to that id column also in Value Clause so your insert query will be like this:-
NOTE:-
You have to calculate and Set Value to #Id variable before using it in Insert Query
Declare #Id as INT
SET #ID = ---- set here with some value which will become Primary key(I think)
Insert into Kitap
(Id,Ad,Yazar,SayfaSayisi,KategoriId)
values
(#Id, #Ad,#Yazar,#SayfaSayisi,#KategoriId)

SQL Server 2012. Copy row into single column on another table

I am working with SQL Server on the AdventureWorks2012 Database. I am working with triggers. I would like to copy any new inserted row into one single column in another table called AuditTable. Basically whenever I insert into the parson.address table, I would like to copy all of the rows into the AuditTable.prevValue column. I know how to insert etc, I am not sure how to write to one column.
Here is the general idea.
USE [AdventureWorks2012]
ALTER TRIGGER [Person].[sPerson] ON [Person].[Address]
FOR INSERT AS INSERT INTO AdventureWorks2012.HumanResources.AuditTable(PrevValue) select
AddressID,AddressLine1,AddressLine2,City, StateProvinceID, PostalCode, SpatialLocation, rowguid, ModifiedDate FROM Inserted
ERROR: The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
Thank you for any assistance. I have searched loads but cannot find the exact solution anywhere.
The error message says it all - you can't insert 9 columns of different types into a single column. Assuming that your destination AuditTable.PrevValue column is NVARCHAR(), you could flatten your insert as follows, by concatenating the columns and casting non-char columns to n*char:
INSERT INTO AdventureWorks2012.HumanResources.AuditTable(PrevValue)
SELECT
N'ID : ' + CAST(AddressID AS NVARCHAR(20)) + N'Address: ' + AddressLine1 +
N', ' +AddressLine2 + ....
FROM Inserted
IMO keeping one long string like this makes the Audit table difficult to search, so you might consider adding SourceTable and possibly Source PK columns.
You could also consider converting your row to Xml and storing it as an Xml column, like this:
create table Audit
(
AuditXml xml
);
alter trigger [Person].[sPerson] ON [Person].[Address] for INSERT AS
begin
DECLARE #xml XML;
SET #xml =
(
SELECT *
FROM INSERTED
FOR XML PATH('Inserted')
);
insert into [MyAuditTable](AuditXml) VALUES (#xml);
end

SQL Server 2012 sequence

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table
Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns,
views, user-defined functions, user-defined aggregates, user-defined
table types, sub-queries, common table expressions, or derived
tables.
T-SQL code:
insert into Job_Update_Log(log_id, update_reason, jobid)
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);
This is my table:
create table Job_Update_Log
(
log_id int primary key ,
update_reason nvarchar(100) ,
update_date date default getdate(),
jobid bigint not null,
foreign key(jobid) references jobslist(jobid)
);
and this is my sequence:
CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ]
AS [int]
START WITH 1
INCREMENT BY 1
NO CACHE
GO
Just get rid of the subselect in the VALUES section, like this:
insert into Job_Update_Log(log_id,update_reason,jobid)
values (next value for Job_Log_Update_SEQ,'grammer fixing',39);
Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx
Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:
insert into Job_Update_Log(log_id,update_reason,jobid)
select next value for Job_Log_Update_SEQ,'grammer fixing',39;
See SQL Fiddle with Demo
I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.
However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:
insert into Job_Update_Log(log_id,update_reason,jobid)
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);
See SQL Fiddle with Demo
Both of these will INSERT the record into the table.
Try this one:
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
(
id int,
Name varchar(50)
);
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);
select * from Products_ext;
/* If you run the above statement two types, you will get the following:-
1 ProductItem
4 ProductItem
*/
drop table Products_ext;
drop sequence idsequence;
------------------------------