how to use select case statement with sql transaction - tsql

i have one crm application. i found query in my db implementation while staff user post reply of inquiry i have to insert new inquiry ans to one table and modify another table data same time. i applied logic of as well as i represent my stored proc. but error occured in this proc.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[InquiryPostReply]
(
#Inquiry_id VARCHAR(50),
#Priority_type VARCHAR(25),
#Status_name VARCHAR(50),
#Inquiry_Content VARCHAR(1024),
#NewId VARCHAR(50) OUT
)
AS
BEGIN
SET NOCOUNT ON;
declare #var1 int
declare #var2 int
declare #uniqueRef char(14)
set #uniqueRef = dbo.UniqueRefNum(rand(), rand(), rand(), rand())
set #var1= (SELECT [Id] FROM [OmStocks].[dbo].[tbl_Status_master] WHERE (Status_name=#Status_name))
set #var2= (SELECT [Id] FROM [OmStocks].[dbo].[tbl_Priority_master] WHERE (Priority_name=#Priority_type))
SELECT
CASE #Status_name
WHEN 'Open' THEN
BEGIN TRAN;
BEGIN TRY
INSERT INTO [OmStocks].[dbo].[tbl_Inquiry_master]
([Id],[Inquiry_id],[Priority_id],[Status_id],[Inquiry_Content],[TimeStamp])
VALUES
(#uniqueRef,#Inquiry_id,#var2,#var1,#Inquiry_Content,CONVERT(DATETIME,GETDATE(), 101))
UPDATE [OmStocks].[dbo].[tbl_Inquiry_History]
SET [Priority_id] = #var2,[Status_id] = #var1,[IsDisplay] = 1,[IsReplied] = 1,[TimeStamp] = CONVERT(DATETIME,GETDATE(), 101)
WHERE (Inquiry_id=#Inquiry_id)
COMMIT TRAN;
END TRY;
WHEN 'Close' THEN
BEGIN TRAN;
BEGIN TRY
INSERT INTO [OmStocks].[dbo].[tbl_Inquiry_master]
([Id],[Inquiry_id],[Priority_id],[Status_id],[Inquiry_Content],[TimeStamp])
VALUES
(#uniqueRef,#Inquiry_id,#var2,#var1,#Inquiry_Content,CONVERT(DATETIME,GETDATE(), 101))
UPDATE [OmStocks].[dbo].[tbl_Inquiry_History]
SET [Priority_id] = #var2,[Status_id] = #var1,[IsDisplay] = 0,[IsReplied] = 1,[TimeStamp] = CONVERT(DATETIME,GETDATE(), 101),[Activity_expire_time] = CONVERT(DATETIME,GETDATE(), 101)
WHERE (Inquiry_id=#Inquiry_id)
COMMIT TRAN;
END TRY;
END
SET #NewId = #uniqueRef
END
error occured like:
Msg 156, Level 15, State 1, Procedure InquiryPostReply, Line 21
Incorrect syntax near the keyword 'BEGIN'.
Msg 102, Level 15, State 1, Procedure InquiryPostReply, Line 31
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Procedure InquiryPostReply, Line 43
Incorrect syntax near ';'.
Msg 102, Level 15, State 1, Procedure InquiryPostReply, Line 46
Incorrect syntax near 'END'.
please help me...

You can't use CASE for this. CASE is an expression that returns a single result, not a statement that can be used for control-of-flow. I do understand that CASE is used that way in some other languages, but it's just not possible in T-SQL.
IF #Status_name = 'Open' THEN
BEGIN
-- do stuff
END
IF #Status_name = 'Close' THEN
BEGIN
-- do other stuff
END

Related

Trying to use temporary table in IBM DB2 and facing issues

I am getting the following error while creating a stored procedure for testing purpose:
SQL Error [42601]: An unexpected token "DECLARE GLOBAL TEMPORARY TABLE
SESSION" was found following "RSOR WITH RETURN FOR". Expected tokens may include: "".. SQLCODE=-104, SQLSTATE=42601, DRIVER=4.21.29
Code:
CREATE OR REPLACE PROCEDURE Test ( IN GE_OutPutType SMALLINT)
----------------------------------------------------------------------------------------------------
DYNAMIC RESULT SETS 1 LANGUAGE SQL
BEGIN
DECLARE C CURSOR WITH RETURN FOR DECLARE GLOBAL TEMPORARY TABLE
SESSION.TEMP (DATE CHAR(10) NOT NULL,
SALARY DECIMAL(9,
2) ,
COMM DECIMAL(9,
2));
INSERT
INTO
SESSION.TEMP (DATE,
SALARY,
COMM) SELECT
VARCHAR_FORMAT(CURRENT_DATE,
'MM/DD/YYYY'),
10.2,
11.5
FROM
sysibm.sysdummy1
IF GE_OutPutType = 1
BEGIN
SELECT
*
FROM
TEMP
ELSEIF GE_OutPutType = 2 SELECT
'HEADER' CONCAT SPACE(1979) CONCAT 'H'
FROM
sysibm.sysdummy1
END OPEN C;
END
Your syntax is not valid.
You must declare your temporary table independently of your cursor.
You cannot combine these in a single statement.
Use dynamic-SQL features to achieve what you need.
Use instead the format:
Declare c1 cursor with return to caller for Statement1
and
set v_cursor_text = 'select ... from session.temp ; `
then use
prepare Statement1 from v_cursor_text;
and before you exit the stored procedure you need to leave the cursor opened:
open c1;
Do study the Db2 online documentation to learn more about these features.
Here is a small fragment of your procedure showing what I mean:
CREATE OR REPLACE PROCEDURE mytest ( IN GE_OutPutType SMALLINT)
DYNAMIC RESULT SETS 1
LANGUAGE SQL
specific mytest
BEGIN
DECLARE v_cursor_text varchar(1024);
DECLARE C1 CURSOR WITH RETURN FOR Statement1;
DECLARE GLOBAL TEMPORARY TABLE SESSION.TEMP (
DATE CHAR(10) NOT NULL,
SALARY DECIMAL(9,
2) ,
COMM DECIMAL(9,
2))
with replace on commit preserve rows not logged;
INSERT INTO SESSION.TEMP (DATE, SALARY, COMM)
SELECT VARCHAR_FORMAT(CURRENT_DATE, 'MM/DD/YYYY'),
10.2,
11.5
FROM sysibm.sysdummy1 ;
if GE_OutPutType = 1
then
set v_cursor_text = 'select * from session.temp';
end if;
if GE_OutPutType = 2
then
set v_cursor_text = 'select ''header'' concat space(1979) concat ''H'' from sysibm.sysdummy1';
end if;
prepare Statement1 from v_cursor_text;
open c1;
END#

TFS 2013 Update 4 to TFS 2015 Update 3 Collection Error

Updating my TFS 2013 Update 4 collection to TFS 2015 Update 3. Using a backup of the production collection data in a DEV location. Did the backup with the production collection being detached. Didn't have any errors. The backup is 254GB.
This is the error currently stopping me from attaching the collection:
Msg 3732, Level 16, State 1, Line 93
Cannot drop type 'typ_ItemSpec2' because it is being referenced by object 'prc_QueryPendingChanges_MS'. There may be other objects that reference this type.
SET XACT_ABORT ON
SET NOCOUNT ON
DECLARE #status INT
DECLARE #procedureName SYSNAME = N'upd_VersionControlToDev14M80_PostSchema'
DECLARE #tfError NVARCHAR(255)
IF EXISTS (
SELECT *
FROM sys.triggers
WHERE name = 'trg_tbl_VCFirstRunProject'
)
BEGIN
DROP TRIGGER trg_tbl_VCFirstRunProject
END
IF EXISTS (
SELECT *
FROM sys.indexes
WHERE name = 'IX_tbl_VCFirstRunProject_OldServerItemPrefix'
AND object_id = OBJECT_ID('dbo.tbl_VCFirstRunProject')
)
BEGIN
-- Delete upgrade-only rows for $\, a few partitions at a time
-- We need dynamic SQL for this to be rerunnable.
EXEC #status = sp_executesql N'
DECLARE #batchStart INT = 1
DECLARE #batchEnd INT
DECLARE #end INT
DECLARE #batchSize INT = 50
-- Get the partition range
SELECT TOP (1)
#end = PartitionId
FROM tbl_VCFirstRunProject
ORDER BY PartitionId DESC
WHILE (#batchStart <= #end)
BEGIN
SET #batchEnd = #batchStart + #batchSize
DELETE tbl_VCFirstRunProject
WHERE PartitionId BETWEEN #batchStart AND #batchEnd
AND OldServerItemPrefix = N''''
OPTION (OPTIMIZE FOR (#batchStart=1, #batchEnd=50))
SET #batchStart = #batchEnd + 1
END
'
IF (#status <> 0)
BEGIN
SET #tfError = dbo.func_GetMessage(500004); RAISERROR(#tfError, 16, -1, #procedureName, #status, N'sp_executesql', N'DELETE tbl_VCFirstRunProject')
RETURN
END
DROP INDEX IX_tbl_VCFirstRunProject_OldServerItemPrefix ON tbl_VCFirstRunProject
END
IF EXISTS (
SELECT *
FROM sys.columns
WHERE object_id = Object_ID(N'dbo.tbl_VCFirstRunProject', N'U')
AND name = N'OldServerItemPrefix'
)
BEGIN
ALTER TABLE tbl_VCFirstRunProject
DROP COLUMN OldServerItemPrefix, NewServerItemPrefix
END
IF TYPE_ID('dbo.typ_BranchObject2') IS NOT NULL
BEGIN
DROP TYPE typ_BranchObject2
END
IF TYPE_ID('dbo.typ_BuildMappingInput2') IS NOT NULL
BEGIN
DROP TYPE typ_BuildMappingInput2
END
IF TYPE_ID('dbo.typ_CreateLabelInput') IS NOT NULL
BEGIN
DROP TYPE typ_CreateLabelInput
END
IF TYPE_ID('dbo.typ_ExpandedChange2') IS NOT NULL
BEGIN
DROP TYPE typ_ExpandedChange2
END
IF TYPE_ID('dbo.typ_ItemSpec2') IS NOT NULL
BEGIN
DROP TYPE typ_ItemSpec2
END
IF TYPE_ID('dbo.typ_LocalPendingChange3') IS NOT NULL
BEGIN
DROP TYPE typ_LocalPendingChange3
END
IF TYPE_ID('dbo.typ_LocalVersion3') IS NOT NULL
BEGIN
DROP TYPE typ_LocalVersion3
END
IF TYPE_ID('dbo.typ_LockConflictCandidate2') IS NOT NULL
BEGIN
DROP TYPE typ_LockConflictCandidate2
END
IF TYPE_ID('dbo.typ_LockObject') IS NOT NULL
BEGIN
DROP TYPE typ_LockObject
END
IF TYPE_ID('dbo.typ_Mapping2') IS NOT NULL
BEGIN
DROP TYPE typ_Mapping2
END
IF TYPE_ID('dbo.typ_PendingAdd2') IS NOT NULL
BEGIN
DROP TYPE typ_PendingAdd2
END
IF TYPE_ID('dbo.typ_PendingChangeObject') IS NOT NULL
BEGIN
DROP TYPE typ_PendingChangeObject
END
IF TYPE_ID('dbo.typ_PendingChangeSecurity') IS NOT NULL
BEGIN
DROP TYPE typ_PendingChangeSecurity
END
IF TYPE_ID('dbo.typ_PendingMerge2') IS NOT NULL
BEGIN
DROP TYPE typ_PendingMerge2
END
IF TYPE_ID('dbo.typ_PendingPropertyChange2') IS NOT NULL
BEGIN
DROP TYPE typ_PendingPropertyChange2
END
IF TYPE_ID('dbo.typ_VersionedItemId') IS NOT NULL
BEGIN
DROP TYPE typ_VersionedItemId
END
None of the standard queries from Microsoft have _MS as a suffix. I suspect that someone hand-tweaked the original prc_QueryPendingChanges and left this around as a backup. In that case you should be able to drop this procedure and retry the upgrade.

two table input parameters in stored procedure

I am working on C# project which needs a stored procedure which will take two table names as inputs.
First table will copy data to a temp table which has two columns URL & channelID. This URL column is then matched with other input table's URL column & if match is found then it will update channel id from temp table to other tables channel ID.
I have written stored procedure as
CREATE PROCEDURE [dbo].[UpdateTables]
#excelTable NVARCHAR(128) ,
#TableName NVARCHAR(128)
AS
Declare #channel_Id nvarchar(50)
Declare #url varchar(400)
BEGIN
Select *
Into #Temp
From QUOTENAME(#excelTable)
END
While EXISTS(SELECT * From #Temp ) > 0
Begin
Select Top 1
#channel_Id = channel_Id, #url = url
From #Temp
update QUOTENAME(#TableName)
set channelid = #channelid
where pagefullurl like '%'+ #url + '%'
Delete #Temp
Where channelid = #channelid
End
I don't have much knowledge in TSQL and my above code has errors.
Incorrect syntax near '>'.
Msg 137, Level 15, State 2, Procedure UpdateTables, Line 20
Must declare the scalar variable "#channelid".
Msg 137, Level 15, State 2, Procedure UpdateTables, Line 22
Must declare the scalar variable "#channelid".
Please suggest what changes needs to done
I don't have MS SQL server handy to test it, but you declare your variable as #channel_Id, and later try to use it as #channelid (without the underscore) so you get errors about the undeclared variable.
I've corrected your SP and this is how it should look
CREATE PROCEDURE [dbo].[UpdateTables]
#excelTable NVARCHAR(128) ,
#TableName NVARCHAR(128)
AS
Declare #channel_Id nvarchar(50)
Declare #url varchar(400)
BEGIN
Select *
Into #Temp
From QUOTENAME(#excelTable)
While EXISTS(SELECT * From #Temp )
Begin
Select Top 1
#channel_Id = channel_Id, #url = url
From #Temp
update QUOTENAME(#TableName)
set channelid = #channel_Id
where pagefullurl like '%'+ #url + '%'
Delete #Temp
Where channelid = #channel_Id
End
END

SQL Server, Error 102, when using CURSOR, creating a dynamic table

I got the following error when using CURSOR in creating temp tables:
(1 row(s) affected)
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '?'.
Msg 208, Level 16, State 0, Line 33
Invalid object name '##TEMP_Branch'.
without CURSOR everything works fine.
Here is the entire code:
declare #TableSchema table
(
Id Int Identity(1,1),
Name nVarchar(50),
DataType nVarchar(50)
)
declare #reportid uniqueidentifier
set #reportid = '597d37c0-563b-42f0-99be-a15000dc7a65'
declare #ttl nvarchar(100)
declare cur CURSOR LOCAL for
SELECT title
FROM ReportItems
where reportid = #reportid
and del = 0
ORder by so
open cur
fetch next from cur into #ttl
while ##FETCH_STATUS = 0 BEGIN
INsert #TableSchema Values(#ttl,'nVarchar(max) NULL')
fetch next from cur into #ttl
end
close cur
deallocate cur
Declare #Statement Varchar(1000)
Select #Statement = 'Create Table [##TEMP_Branch](FieldID Varchar(50)'
Select #Statement = COALESCE(#Statement +',','') + Name + ' ' + DataType from #TableSchema
Select #Statement = #Statement + ')'
EXEC(#Statement)
Select * from ##TEMP_Branch
drop table ##TEMP_Branch
Any kind help would be HIGHLY appreciated.
use a table varible
Declare #TEMP_Branch TABLE
(
FieldID varchar(50)
)
it work as regular table, without relation, and dont have to drop, for lager data process, make a permanent table to temporary store the data and after deleto or truncate it
You probably have a title in the ReportItems table that has a blank space or other bad character (question mark) in it.
The first error looks like it coming out of the EXEC(#Statement) because the table definition is invalid.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '?'.
The second error is probably Select * from ##TEMP_Branch being executed against a temp table that doesn't exist:
Msg 208, Level 16, State 0, Line 33
Invalid object name '##TEMP_Branch'.

Getting value from stored procedure in another stored procedure

Sorry, lots of code coming up..
I saw another question like this that used output parameters. I'm using the RETURN statement to return the value I want to use.
I have one stored procedure InsertMessage that looks like this:
ALTER PROCEDURE dbo.InsertNewMessage
(
#messageText text,
#dateTime DATETIME,
#byEmail bit,
#bySMS bit
)
AS
DECLARE #NewId int
BEGIN
BEGIN TRANSACTION
INSERT INTO MessageSet VALUES (#byEmail, #bySMS, #dateTime, #messageText)
SET #NewId = SCOPE_IDENTITY()
COMMIT
END
RETURN #NewId
which another stored procedure uses:
ALTER PROCEDURE dbo.InsertMessageFromUserToGroup
(
#userEmail nvarchar(256),
#groupId int,
#messageText text,
#bySMS bit,
#byEmail bit
)
AS
--Inserts a new message to a group
DECLARE #messageId int
DECLARE #dateTime DATETIME = GETDATE()
--First check if user is a part of the group
IF NOT EXISTS (SELECT userEmail FROM UserToGroupSet WHERE userEmail = #userEmail AND groupId = #groupId)
RETURN 'User not part of group'
ELSE --User is a part of the group, add message
BEGIN
BEGIN TRANSACTION
SET #messageId = [dbo].[InsertNewMessage](#messageText, #dateTime, #bySMS, #byEmail)
INSERT INTO MessageToUser VALUES(#userEmail, #messageId)
INSERT INTO MessageToGroup VALUES(#messageId, #groupId)
COMMIT
END
The row that causes the trouble and of which I'm unsure how to handle is this one:
SET #messageId = [dbo].[InsertNewMessage](#messageText, #dateTime, #bySMS, #byEmail)
The syntax seems ok because I can save it. When I run it I get the error message:
Running [dbo].[InsertMessageFromUserToGroup] ( #userEmail = test#test.com, #groupId = 5, #messageText = sdfsdf, #bySMS = false, #byEmail = true ).
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.InsertNewMessage", or the name is ambiguous.
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
No rows affected.
(0 row(s) returned)
#RETURN_VALUE =
Finished running [dbo].[InsertMessageFromUserToGroup].
It seems as if the other stored procedure can't be found. I've tried different ways of calling the procedure but everything else fails as well. Any suggestions?
Try changing
SET #messageId = [dbo].[InsertNewMessage](#messageText, #dateTime, #bySMS,
#byEmail)
to
EXEC #messageId = [dbo].[InsertNewMessage] #messageText, #dateTime, #bySMS,
#byEmail
Notice that SET has been changed to EXEC, and the parentheses have been removed from the parameters.
See the example in the MSDN documenation at the end of the article for more information.