Removing a column name from a stored procedure - sql

I created a stored procedure for insert query and run the code. Successfully it executed. Now I want to remove one column from from that SP. How to do it?
CREATE PROCEDURE dbo.NewTerms_Insert
#ListID nvarchar(50) ,
#TimeCreated datetime ,
#TimeModified datetime ,
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
ListID ,
TimeCreated ,
TimeModified ,
)
VALUES
(
#ListID ,
#TimeCreated ,
#TimeModified ,
)
END
GO
I want to remove ListID from this Stored Procedure named dbo.NewTerms_Insert. How to do it?

Just ALTER the procedure with removing that column.
ALTERPROCEDURE dbo.NewTerms_Insert
#TimeCreated datetime ,
#TimeModified datetime ,
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,
TimeModified ,
)
VALUES
(
#TimeCreated ,
#TimeModified ,
)
END
GO

Remove the column and alter the procedure:
ALTER PROCEDURE dbo.NewTerms_Insert
#TimeCreated datetime ,
#TimeModified datetime
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,
TimeModified
)
VALUES
(
#TimeCreated ,
#TimeModified
)
END
GO

Simply modify the procedure as you want (changing its interface and/or its body).
Before executing that script, run the following in order to make sure the previous version is removed:
IF OBJECT_ID('dbo.NewTerms_Insert', 'P') IS NOT NULL
DROP PROCEDURE dbo.NewTerms_Insert;
GO
Personally, I find it good practise to insert that fragment at the beginning of each script that creates/modifies a procedure or whatever.

Alter procedure and remove list column from insert statement and from value
Alter PROCEDURE dbo.NewTerms_Insert
(
#ListID nvarchar(50) ,
#TimeCreated datetime ,
#TimeModified datetime
)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO dbo.NewTerms
(
TimeCreated ,TimeModified
)
VALUES
(
#TimeCreated ,
#TimeModified
)
END
GO

Related

INSERT to a table using SELECT and VALUES at the same time

how can I insert to a table using values in different way? preferably no temp table. below is my stored procedure code, but i get errors on insert
CREATE PROCEDURE setBARS
-- Add the parameters for the stored procedure here
#BUSINESSAREANAME nvarchar(50),
#STAFFNAME nvarchar(50),
#ROLENAME nvarchar(50),
#BARSSTARTDATE date,
#BARSENDDATE date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
WITH t1 (BUSINESSAREAID) AS (SELECT BUSINESSAREAID FROM BUSINESSAREA WHERE BUSINESSAREANAME = #BUSINESSAREANAME),
t2 (STAFFID) AS (SELECT STAFFID FROM STAFF WHERE STAFFNAME = #STAFFNAME),
t3 (ROLEID) AS (SELECT ROLEID FROM ROLE WHERE ROLENAME = #ROLENAME)
INSERT INTO BARS ([BUSINESSAREAID],[STAFFID],[ROLEID],[BARSSTARTDATE],[BARSENDDATE])
VALUES ((SELECT t1.BUSINESSAREAID, t2.STAFFID, t3.ROLEID FROM t1,t2,t3), #BARSSTARTDATE, #BARSENDDATE)
END
GO
You should be able to include the values directly in the SELECT statement:
INSERT INTO [BARS]
(
[BUSINESSAREAID]
, [STAFFID]
, [ROLEID]
, [BARSSTARTDATE]
, [BARSENDDATE]
)
SELECT
[t1].[BUSINESSAREAID]
, [t2].[STAFFID]
, [t3].[ROLEID]
, #BARSSTARTDATE
, #BARSENDDATE
FROM [t1]
, [t2]
, [t3];
Try This
insert into bars([BUSINESSAREAID],[STAFFID],[ROLEID],[BARSSTARTDATE][BARSENDDATE])
SELECT t1.BUSINESSAREAID, t2.STAFFID, t3.ROLEID FROM t1,t2,t3, #BARSSTARTDATE, #BARSENDDATE
why not put all the values on a variable for example;
declare #val1
set #val1 = (select top 1 businessareaid from t1)
declare #val2
set #val1 = (select top 1 staffid from t2)
insert into bars (val1,val2)
select #val1 , #val2

Share auto-increment value from SQL stored procedure

I have a stored procedure that inserts data on a table with an auto-increment id (name of 'requestid'). As I insert data into it using the procedure, I want to take the value of the auto-increment field and use it on another query to the same stored procedure. How do I do that? Thank you in advance for your time.
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
END
Try
CREATE PROCEDURE [dbo].[sp_Create_new_request]
#employeeid INT ,
#requestdate DATETIME ,
#deliverdate DATETIME ,
#totalcost MONEY,
requestid INT = NULL OUT
AS
BEGIN
INSERT INTO dbo.Requests
(
EmployeeID ,
RequestDate ,
DeliverDate ,
TotalCost
)
VALUES
(
#employeeid ,
#requestdate ,
#deliverdate ,
#totalcost
)
SET #requestid = SCOPE_IDENTITY();
END
You should not use auto increment instead use sequence to increment and then you can reuse that value anywhere.
You can use also :
IDENT_CURRENT ('dbo.Requests')
Information about IDENT_CURRENT
http://technet.microsoft.com/en-us/library/ms175098.aspx

How to generate and manually insert a uniqueidentifier in SQL Server?

I'm trying to manually create a new user in my table but am finding it impossible to generate a "UniqueIdentifier" type without the code throwing an exception...
Here is my example:
DECLARE #id uniqueidentifier
SET #id = NEWID()
INSERT INTO [dbo].[aspnet_Users]
([ApplicationId]
,[UserId]
,[UserName]
,[LoweredUserName]
,[LastName]
,[FirstName]
,[IsAnonymous]
,[LastActivityDate]
,[Culture])
VALUES
('ARMS'
,#id
,'Admin'
,'admin'
,'lastname'
,'firstname'
,0
,'2013-01-01 00:00:00'
,'en')
GO
Throws this exception ->
Msg 8169, Level 16, State 2, Line 4
Failed to convert a character string to uniqueidentifier.
I am using the NEWID() method but it's not working...
http://www.dailycoding.com/Posts/generate_new_guid_uniqueidentifier_in_sql_server.aspx
ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:
DECLARE #TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE #UNIQUEX UNIQUEIDENTIFIER
SET #UNIQUEX = NEWID();
INSERT INTO #TTEST
(TEST)
VALUES
(#UNIQUEX);
SELECT * FROM #TTEST
Therefore I would say it is safe to assume that ApplicationId is not the correct data type.
Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .
*Your parameter order is passed wrongly ,
Parameter #id should be passed as first argument, but in your script it is placed in second argument..*
So error is raised..
Please refere sample script:
DECLARE #id uniqueidentifier
SET #id = NEWID()
Create Table #temp1(AppId uniqueidentifier)
insert into #temp1 values(#id)
Select * from #temp1
Drop Table #temp1
Check your column data type should be unique identifier
And you are using the correct order when inserting values
INSERT INTO [dbo].[aspnet_Users]
([ApplicationId],[UserId],[UserName],[LoweredUserName],[LastName]
,[FirstName],[IsAnonymous],[LastActivityDate],[Culture])
VALUES ('ARMS',NEWID(),'Admin','admin','lastname','firstname,0
,'2013-01-01 00:00:00','en')

SQL Triggers - how do I get the updated value?

How do I get the value of the updated record in a SQL trigger - something like this:
CREATE TRIGGER TR_UpdateNew
ON Users
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
EXEC UpdateProfile (SELECT UserId FROM updated AS U);
END
GO
Obviously this doesn't work, but you can see what I am trying to get at.
Provide you are certain that only one value will ever be updated, you can do this...
CREATE TRIGGER TR_UpdateNew
ON Users
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #user_id INT
SELECT
#user_id = inserted.UserID
FROM
inserted
INNER JOIN
deleted
ON inserted.PrimaryKey = deleted.PrimaryKey
-- It's an update if the record is in BOTH inserted AND deleted
EXEC UpdateProfile #user_id;
END
GO
If multiple values can be updated at once, only one of them will get processed by this code. (Although it won't error.)
You could use a cursor, or if it's SQL Server 2008+ you can use table variables.
Or, more commonly, just move the StoredProcedure code into the trigger.
Based on my knowledge you would need to create a CURSOR to loop through all the updated values to execute the UpdateProfile procedure. Keep in mind this will slow down your update process.
Declare #UserID int --Assuming
Declare UpdateProfile_Cursor Cursor for Select UserID From inserted;
Open Cursor UpdateProfile_Cursor;
Fetch Next from UpdateProfile_Cursor Into #UserID;
While ##FETCH_STATUS == 0
Begin
Exec UpdateProfile #UserID
Fetch Next from UpdateProfile_Cursor Into #UserID;
End
CLOSE UpdateProfile_Cursor
DEALLOCATE UpdateProfile_Cursor
My syntax may be a little off but this will give you the desired effect. Again, consider revising your logic to handle multiple updates as using cursors is resource intensive.
You can do something like this example where I'm logging changes to a transaction history table:
create table dbo.action
(
id int not null primary key ,
description varchar(32) not null unique ,
)
go
insert dbo.action values( 1 , 'insert' )
insert dbo.action values( 2 , 'update' )
insert dbo.action values( 3 , 'delete' )
go
create table dbo.foo
(
id int not null identity(1,1) primary key ,
value varchar(200) not null unique ,
)
go
create table dbo.foo_history
(
id int not null ,
seq int not null identity(1,1) ,
action_date datetime not null default(current_timestamp) ,
action_id int not null foreign key references dbo.action ( id ),
old_value varchar(200) null ,
new_value varchar(200) null ,
primary key nonclustered ( id , seq ) ,
)
go
create trigger foo_update_01 on dbo.foo for insert, update , delete
as
set nocount on
set xact_abort on
set ansi_nulls on
set concat_null_yields_null on
--
-- record change history
--
insert dbo.foo_history
(
id ,
action_id ,
old_value ,
new_value
)
select id = coalesce( i.id , d.id ) ,
action_id = case
when i.id is not null and d.id is null then 1 -- insert
when i.id is not null and d.id is not null then 2 -- update
when i.id is null and d.id is not null then 3 -- delete
end ,
old_value = d.value ,
new_value = i.value
from inserted i
full join deleted d on d.id = i.id
go
But you can use the same sort of technique, mix it up a bit and pass the entire set of values to a stored procedure, like I do in the following example (using the table schema above).
First, create a stored procedure that expects a particular temp table to exist at runtime, thus:
--
-- temp table must exist or the stored procedure won't compile
--
create table #foo_changes
(
id int not null primary key clustered ,
action_id int not null ,
old_value varchar(200) null ,
new_value varchar(200) null ,
)
go
--
-- create the stored procedure
--
create procedure dbo.foo_changed
as
--
-- do something useful involving the contents of #foo_changes here
--
select * from #foo_changes
return 0
go
--
-- drop the temp table
--
drop table #foo_changes
go
Once you've done that, create a trigger that will create and populate the temp table expected by the stored procedure and then execute the stored procedure:
create trigger foo_trigger_01 on dbo.foo for insert, update , delete
as
set nocount on
set xact_abort on
set ansi_nulls on
set concat_null_yields_null on
--
-- create the temp table. This temp table will be in scope for any stored
-- procedure executed by this trigger. It will be automagickally dropped
-- when trigger execution is complete.
--
-- Any changes made to this table by a stored procedure — inserts,
-- deletes or updates are, of course, visible to the trigger upon return
-- from the stored procedure.
--
create table #foo_changes
(
id int not null primary key clustered ,
action_id int not null ,
old_value varchar(200) null ,
new_value varchar(200) null ,
)
--
-- populate the temp table
--
insert #foo_changes
(
id ,
action_id ,
old_value ,
new_value
)
select id = coalesce( i.id , d.id ) ,
action_id = case
when i.id is not null and d.id is null then 1 -- insert
when i.id is not null and d.id is not null then 2 -- update
when i.id is null and d.id is not null then 3 -- delete
end ,
old_value = d.value ,
new_value = i.value
from inserted i
full join deleted d on d.id = i.id
--
-- execute the stored procedure. The temp table created above is in scope
-- for the stored procedure, so it's able to access the set of changes from
-- the trigger.
--
exec dbo.foo_changed
go
That's about all there is to it. It's simple, it's easy, it works for change sets of any size. And, it's safe, with no race conditions or collisions with other users in the system.

Get SQL Insert to work when PK is supplied or NOT

I have the following stored procedure:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
-- If #ServerEnvironmentId was not supplied.
IF (#ServerEnvironmentId IS NULL)
BEGIN
-- Get the ServerEnvironmentId.
SELECT #ServerEnvironmentId = ServerEnvironmentId
FROM #APPL_ServerEnvironment
END
The ServerEnvironmentId column is a primary key with a default set on it, which is (newsequentialid()).
I need this stored procedure to work for 2 scenarios:
Value supplied for ServerEnvironmentId - WORKS.
Value not supplied for ServerEnvironmentId - DOES NOT WORK - CANNOT INSERT NULL VALUE. I thought by setting a default on this column this would be fine.
Someone please help to ammend this procedure so that it may work for both scenarios. Solution needs to have minimal changes as all sp's currently following this trend.
Default values are only applied on inserts if the column is not included in the INSERT list. I'd recommend the following not entirely trivial change (I've commented out the lines to be removed):
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
---- Stores the ServerEnvironmentId.
--DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF #ServerEnvironmentName is null
SET #ServerEnvironmentName = newid()
-- Insert the data into the table.
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
--OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
---- If #ServerEnvironmentId was not supplied.
--IF (#ServerEnvironmentId IS NULL)
--BEGIN
-- -- Get the ServerEnvironmentId.
-- SELECT #ServerEnvironmentId = ServerEnvironmentId
-- FROM #APPL_ServerEnvironment
--END
The default constraint will not be used by this procedure, but you can leave it in place if there are other places where rows may be added to the table.
(My first answer was long and so it this one, so I'm posting a second answer.)
I missed that you were using NewSequentialId. Again, if a column is specified within the insert statement, any DEFAULT values assigned to that column will not be used [unless you use the DEFAULT keyword in the INSERT statement, but that's still all or nothing--you can't say "if #Var is null then DEFAULT"]. I think you are stuck with simple branching and semi-redundant code, along the lines of:
ALTER Procedure dbo.APPL_ServerEnvironmentInsert
(
#ServerEnvironmentName varchar(50),
#ServerEnvironmentDescription varchar(1000),
#UserCreatedId uniqueidentifier,
#ServerEnvironmentId uniqueidentifier OUTPUT
)
WITH RECOMPILE
AS
-- Stores the ServerEnvironmentId.
DECLARE #APPL_ServerEnvironment TABLE (ServerEnvironmentId uniqueidentifier)
IF #ServerEnvironmentId is null
BEGIN
-- ServerEnvironmentId not provided by user, generate during the insert
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId
)
-- Get the new ServerEnvironmentId
SELECT #ServerEnvironmentId = ServerEnvironmentId
FROM #APPL_ServerEnvironment
END
ELSE
BEGIN
-- ServerEnvironmentId is provided by user
INSERT INTO APPL_ServerEnvironment WITH(TABLOCKX)
(
ServerEnvironmentName,
ServerEnvironmentDescription,
DateCreated,
UserCreatedId,
ServerEnvironmentId
)
OUTPUT Inserted.ServerEnvironmentId INTO #APPL_ServerEnvironment
VALUES
(
#ServerEnvironmentName,
#ServerEnvironmentDescription,
GETDATE(),
#UserCreatedId,
#ServerEnvironmentId
)
END
(Why lock the entire table during the insert?)
Help to Simplify SQL Insert which uses NEWSEQUNETIALID() column default