sql procedure auto iincrement if exist - sql

procedure [dbo].[InsertSortCode] (
#Sortcode varchar(25)
, #verbiage varchar(200) )
as
begin
SET IDENTITY_INSERT appmaster on
insert into AppMaster(MainID,SortCode) values (
(select MAX(mainid)
from AppMaster) + 1, #Sortcode )
SET IDENTITY_INSERT appmaster off
insert into Verbiage(MenueID,verbiage) values (
(select MAX(mainid)
from AppMaster), #verbiage )
the above is my stored procedure it is working perfectly fine but there is an error if there is no data in the database
the problem is with max function ,if the is no data in database
it cannot max out the id it works only if there is already some data
with its id in that databse
need to figure out how to use the exist statement on this SP so that it can work with both empty table and filled table

You can try following query:-
insert into AppMaster(MainID,SortCode) values (
(select ISNULL(MAX(mainid),0)
from AppMaster) + 1, #Sortcode )
So if MAX(mainid) is null it will return as 0 and add 1 to that.

Related

Using the identity column to add a value to a computed column

At times I need to store a temporary value to a field. I have a stored procedure that adds it using:
Insert new record first then
SELECT #Record_Value = SCOPE_IDENTITY();
UPDATE ADMIN_Publication_JSON
SET NonPubID = CAST(#Record_Value as nvarchar(20)) + '_tmp'
WHERE RecID = #Record_Value
It simply takes the identity value and adds an '_tmp' to the end. Is there a way that I can create a default value in the table that would do that automatically if I did not insert a value into that field?
The NonPubID column is just a NVARCHAR(50).
Thanks
You could write a trigger, that replaces NULL with that string upon INSERT.
CREATE TRIGGER admin_publication_json_bi
ON admin_publication_json
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
UPDATE apj
SET apj.nonpubid = concat(convert(varchar(20), i.id), '_tmp')
FROM admin_publication_json apj
INNER JOIN inserted i
ON i.id = apj.id
WHERE i.nonpubid IS NULL;
END;
db<>fiddle
Downside: You cannot explicitly insert NULLs for that column, should that be desired.
Check out NewKey col below:
CREATE TABLE #Table
(
ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY CLUSTERED,
IDValue VARCHAR(1) ,
ModifiedDT DATETIME NULL,
NewKey AS ( CONVERT(VARCHAR(100),ID)+'_Tmp' )
)
INSERT #Table( IDValue, ModifiedDT )
SELECT 'A', GETDATE()
UNION ALL
SELECT 'Y', GETDATE() - 1
UNION ALL
SELECT 'N', GETDATE() - 5
SELECT * FROM #Table

Delete and Insert Into

I'm looking to execute a stored procedure everyday where it will firstly delete the data within a specified table and then insert the new data in.
My stored procedure looks roughly like this
ALTER PROCEDURE [dbo].[SP_Name]
AS BEGIN
WITH CTE_Name as
( select
Title,
First_Name,
Surname
From table
)
DELETE [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
Select * from CTE_NAME
END
When I execute the query I get the error invalid object name 'CTE_NAME'
I have tried removing the 'DELETE [dbo].[NEW_TABLE]' line and upon doing this the stored procedure does run and does insert the data into the table.
I'm using SQl Management Studio 2012
I think you need to separate your With by adding a semicolon in front of it
below code should work
DECLARE #TABLE TABLE (
id VARCHAR(100)
)
DELETE FROM #TABLE
;WITH CTE_Name AS
(
SELECT id FROM OtherTable
)
INSERT INTO #TABLE
SELECT id FROM CTE_Name
You could try this code:
ALTER PROCEDURE [dbo].[SP_Name] AS
BEGIN
DECLARE #helperTbl TABLE (Title varchar(100), First_Name varchar(100), Surname varchar(100))
INSERT INTO #helperTbl
SELECT Title,
First_Name,
Surname
FROM [table]
DELETE FROM [dbo].[NEW_TABLE]
INSERT INTO [dbo].[NEW_TABLE]
SELECT * FROM #helperTbl
END

Insert multiple rows using single insert statement

I am trying to insert into table variable using following query.
but its throwing an error.
Please help on inserting multiple selects using single insert statement.
DECLARE #AddressRecordsToPurge TABLE
(
RowID INT NOT NULL PRIMARY KEY IDENTITY(1,1),
GUIDValue Nvarchar(max) ,
GuidColumn Nvarchar(max) ,
GuidTable Nvarchar(max)
)
Insert Into #AddressRecordsToPurge values ( (Select
EMPLOYMENTSEQUENCENUMBER FROM ACCOUNTANTSREFERENCE WHERE
CustomerNumber = #CustomerNumber AND Customerversionnumber =
#CustomerVersionNumber AND EMPLOYMENTSEQUENCENUMBER IS NOT
NULL), 'EMPLOYMENTSEQUENC ENUMBER', 'ACCOUNTANTSREFERENCE');
My select statement returns multiple values and I want to have it this way only. Please help!
Your syntax is slightly off:
Insert Into #AddressRecordsToPurge (GuidValue, GuidColumn, GuidTable)
SELECT EMPLOYMENTSEQUENCENUMBER, 'EMPLOYMENTSEQUENCENUMBER', 'ACCOUNTANTSREFERENCE'
FROM ACCOUNTANTSREFERENCE
WHERE CustomerNumber = #CustomerNumber
AND Customerversionnumber = #CustomerVersionNumber
AND EMPLOYMENTSEQUENCENUMBER IS NOT NULL;

Stored Procedure that updates fields with different values

I am using SQL Server.
I need to create a stored procedure that will update the Data field (table bellow) with different value for every ID value. (the values in the Data fields depend on the user input).
ID | Data
---------
1 | NULL
2 | NULL
3 | NULL
For example:
if ID = 1, Data should be "Test1"
The ID and Data pairs should somehow be input parameters to the stored procedures.
Is this possible, or I'll have to call simple update procedure for every ID/Data pair?
You need to use XML for sending data for multiple rows. For your current problem prepare (generate dynamically) an xml like below.
'<NewDataSet><Table><Id>1</Id><Data>test1</Data></Table><Table><Id>2</Id><Data>test2</Data></Table></NewDataSet>'
Then Prepare a procedure like below.
CREATE PROC [dbo].[UpdateMultipleRecords]
(
#XmlString VARCHAR(MAX)
)
AS
BEGIN
SET NOCOUNT ON;
CREATE TABLE #DATA
(
Id int,
Data varchar(50) NULL
)
DECLARE #DocHandle int
EXEC sp_xml_preparedocument #DocHandle OUTPUT, #XmlString
INSERT INTO #DATA
SELECT Id,Data
FROM OPENXML (#DocHandle, '/NewDataSet/Table',2)
WITH
(
Id int,
Data varchar(50)
)
EXEC sp_xml_removedocument #DocHandle
UPDATE [dbo].[Table1] SET DATA=D.Data
FROM [dbo].[Table1] T INNER JOIN #DATA D ON T.ID=D.Id
IF (SELECT OBJECT_ID('TEMPDB..#DATA')) IS NOT NULL DROP TABLE #DATA
END
And call the procedure as
[UpdateMultipleRecords] '<NewDataSet><Table><Id>1</Id><Data>Test1</Data></Table><Table><Id>2</Id><Data>Test2</Data></Table></NewDataSet>'
You need user-defined table types for this:
Try this:
-- test table
create table yourtable(id int not null, data [varchar](256) NULL)
GO
-- test type
CREATE TYPE [dbo].[usertype] AS TABLE(
[id] [int] not null,
[Data] [varchar](256) NULL
)
GO
-- test procedure
create procedure p_test
(
#tbl dbo.[usertype] READONLY
) as
BEGIN
UPDATE yourtable
SET data = t.data
FROM yourtable
JOIN
#tbl t
ON yourtable.id = t.id
END
go
-- test data
insert yourtable(id)
values(1),(2),(3)
go
Test of script:
declare #t [dbo].[usertype]
insert #t values(1,'hello'),(2,'world')
exec p_test #t
select * from yourtable
Result:
id data
1 hello
2 world
3 NULL
You can use another table with your values as a Source for the update
update t
set
Data = src.Data
from tableDestination t
inner join sourceTable src on
t.ID = src.ID

Select only few columns from procedure and insert into table

I have a stored procedure that returns 6 columns. But I want to take only 2 columns and insert them into my table variable.
DECLARE #CategoryTable TABLE(
CategoryId Int NOT NULL,
Name nvarchar(255) NOT NULL
)
INSERT INTO #CategoryTable EXEC [GetAllTenantCategories] #TenantId
When I run this
Column name or number of supplied values does not match table
definition
How to insert only specified columns from a stored procedure?
I do not want to use SELECT INTO as it is not supported by SQL Azure
Tried below and got Invalid object name '#Temp'
DECLARE #CategoryTable TABLE(
CategoryId Int NOT NULL,
Name nvarchar(255) NOT NULL
)
INSERT INTO #Temp EXEC [GetAllTenantCategories] 1
INSERT INTO #CategoryTable (CategoryId, Name)
SELECT CategoryId, Name from #Temp
DROP TABLE #Temp
You can create a temp table first and the INSERT the required columns in your table variable.
CREATE TABLE #temp
(
your columns and datatype
)
INSERT INTO #temp
EXEC [GetAllTenantCategories] #TenantId
Then you can,
DECLARE #CategoryTable TABLE(
CategoryId Int NOT NULL,
Name nvarchar(255) NOT NULL
)
INSERT INTO #CategoryTable (CategoryId, Name)
select CategoryId, Name from #temp
Also drop the #temp table,
DROP TABLE #temp
Refer the points taken from https://www.simple-talk.com/sql/performance/execution-plan-basics/
When the Estimated Plan is Invalid
In some instances, the estimated plan won't work at all. For example, try generating an estimated plan for this simple bit of code:
CREATE TABLE TempTable
(
Id INT IDENTITY (1 , 1 )
,Dsc NVARCHAR (50 )
);
INSERT INTO TempTable ( Dsc )
SELECT [Name]
FROM [Sales] .[Store] ;
SELECT *
FROM TempTable ;
DROP TABLE TempTable ;
You will get this error:
Invalid object name 'TempTable'.
The optimizer, which is what is used to generate Estimated Execution plans, doesn't execute T-SQL.
It does run the stateĀ­ments through the algebrizer , the process outlined earlier that is responsible for verifying the names of database objects. Since the query has not yet been executed, the temporary table does not yet exist. This is the cause of the error.
Running this same bit of code through the Actual execution plan will work perfectly fine.
Hope you got why your temp table approach not worked :) Because you might tried as T-SQL
We can use OPENQUERY
SELECT EmployeeID,CurrentSalary INTO #tempEmp
FROM OPENQUERY(LOCALSERVER,'Exec TestDB.dbo.spEmployee')