The following doesn't work, any ideas?
DECLARE #seed int
// set #seed to some value
ALTER TABLE MyTable ADD MyTableId int identity (#seed, 1)
Result:
Msg 102,
Incorrect syntax near '#seed'
I used DBCC CHECKIDENT ('MyTable', RESEED, #seed) which seems to work.
Related
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
when trying to write the output of a stored procedure into a temp table, I get the error message
Msg 208, Level 16, State 0, Line 4
Invalid object name '#tblTemp '.
My query is this:
DECLARE #group_name varchar(250)
SET #group_name = 'somevalue'
INSERT INTO #tblTemp EXEC mySchema.sp_MyStoredProc #group_name OUTPUT
SELECT *
FROM #tblTemp
DROP TABLE #tblTemp
What is wrong here?
Thanks for your help!
To use temp table this way in INSERT INTO you should define this table first.
CREATE TABLE #tblTemp(
ID int,
....
)
In T-SQL a temp table can be created automatically using following command:
select * into #tblTemp
from table
You can use this syntax in your case with stored procedure results using OPENROWSET.
Here is the answer on SO which can help
You need to create the #temp table with e.g. a CREATE TABLE statement before you can INSERT INTO it.
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.
Does someone know how can I return the ##Identity when using T-Sql?
Something like this:
set #Sql = "insert into table....values()..."
exec #sql
return ##Identity
It looks like one of your implicit requirements is the execution of dynamic SQL. While I'd advise against this, you can accomplish what you're looking for with this:
set #Sql = 'insert into table....values()...; select SCOPE_IDENTITY()'
exec(#Sql)
Like this:
INSERT INTO Table(...)
OUTPUT INSERTED.IdColumn
VALUES(...)
INSERT INTO TableName (Field1, Field2, Field3) VALUES (1, 2, 3);
SELECT SCOPE_IDENTITY();
This is a multi-statement batch, so I'm not sure that every client library will return values the same way; in classic ADO, for example, it's possible that you might need to advance to the next recordset before you can read the value. But if you're using ADO.NET, I know that you can just use ExecuteScalar on the whole string above, and it will return your SCOPE_IDENTITY value just fine.
Caution: ADO.NET will return the value as a decimal, not an int like you might expect. This is because SCOPE_IDENTITY, for whatever reason, is typed as numeric(38,0). So you either need to cast the ExecuteScalar result to decimal before you cast it to int, or you need to SELECT CAST(SCOPE_IDENTITY() AS INT) (assuming your IDENTITY field is an INT, and not some larger numeric type).
Append ";select ##identity" to your insert statement:
insert into tab (x,y,z) values (a,b,c); select ##identity
The returned value is the ID (use ExecuteScalar)
You can use this
Insert into Table(Col2, Col3)
output inserted.Id
values ('xyz', 'abc')
Where Id is your Identity field
I would like to do the following. Basically have a stored procedure call another stored procedure that returns a table. How is this done?
ALTER PROC [GETSomeStuff]
AS
BEGIN
#table = exec CB_GetLedgerView #accountId, #fromDate, #toDate, #pageSize, #pageNumber, #filter, #status, #sortExpression, #sortOrder, #virtualCount OUTPUT
Select * from #table
--Do some other stuff here
END
The target of a stored procedure has to be a temp or actual table so you can
Insert into #table exec CB_GetLedgerView #accountId, #fromDate,
#toDate, #pageSize, #pageNumber,
#filter, #status, #sortExpression,
#sortOrder, #virtualCount OUTPUT
If the output result set of the stored procedure does not match the ordinal positions and count of the rows in the target table, specify a column list.
The temporary-table approach, at least as expressed above, didn't work for me. You can use a variable, just as easily.
DECLARE #return_value INT
DECLARE #tblOutputTable TABLE(Col1 BIT NOT NULL, Col2 INT NOT NULL)
INSERT INTO #tblOutputTable EXEC #return_value = [dbo].[SomeSp] #Param1 = 15, #Param2 = 2
Maybe your example isn't really representative, but the first question I'd have have is, do you really need to make this two procedures, at the cost of greater complexity? Decomposition like this is somewhat of an antipattern with SQL. (Although some will disagree, but I've seen this discussed with majority agreement here on SO.)