unqiueidenfitier is not compatible with type int SQL Server Procedure - sql

I have the following procedure for inserting into a user table:
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters
-- command (Ctrl-Shift-M) to fill in the parameter
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Andy Armstrong
-- Create date:
-- Description:
-- =============================================
CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15)
AS
BEGIN
DECLARE #GUID UNIQUEIDENTIFIER
SET #GUID = NEWID();
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT INTO tblMemberLogin
(
UserID,
LoginName,
LoginPassword
)
VALUES
(
#GUID,
#LoginName,
#LoginPassword
)
RETURN #GUID
END
GO
However when I execute it I get the following error:
Msg 206, Level 16, State 2, Procedure db_SignupAddLogin, Line 34
Operand type clash: uniqueidentifier is incompatible with int
I cannot quite workout why as i am not referencing an int anywhere.
My Schema for tblMemberLogin looks like this:
UserID(PK,uniqueidentifier,notnull)
LoginName(nchar(15),not null)
LoginPassword(nchar(15),not null)
Please help!

RETURN can only be used with an int. You can simply use a SELECT query to retrieve the value of variable #GUID.
Reference: http://technet.microsoft.com/en-us/library/ms174998(v=sql.110).aspx

get rid of RETURN #GUID and you should be good to go.

In SQL Server, stored procedures may only return integer values. SQL Server RETURN
If you want to return data from a stored procedure other than an integer, you can use an output parameter: Returning Data from Stored Procedures
You declare the output parameter along with your input parameters:
CREATE PROCEDURE CREATE PROCEDURE db_SignupAddLogin
-- Add the parameters for the stored procedure here
#LoginName VARCHAR(15),
#LoginPassword VARCHAR(15),
#NewGuid UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET #NewGuid = NEWID();
-- rest of procedure
END
And then use the output parameter:
DECLARE #NewLoginGuidFromSP UNIQUEIDENTIFIER
EXECUTE db_SignupAddLogin 'Username', 'password', #NewGuid = #NewLoginGuidFromSP OUTPUT;

Related

Why would a stored procedure return a 0 and the selected id?

I have a stored procedure like this:
CREATE PROCEDURE [dbo].[create_myNewId]
(#parentId BIGINT)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [Mapping] (ParentId)
VALUES (#parentId)
SELECT SCOPE_IDENTITY();
END
This, when run on its own, returns the new id that has been assigned to the new row that's inserted with the parent id. However, when I do something like this:
DECLARE #NewId int
EXEC #NewId = create_myNewId #parentId = 33333
SELECT #NewId
When running this, the output window shows the result of the stored procedure, which returns an Id but #NewId always is 0. I fixed this by changing the stored procedure to use RETURN SCOPE_IDENTITY() but I was wondering why SELECT didn't work in this case?
I have my suspicions that it's something around the 0 being the success status being returned first from the stored procedure rather than the result, but was curious why this doesn't then happen when called directly from the client.
No! Write the procedure the right way:
CREATE PROCEDURE [dbo].[create_myNewId] (
#parentId bigint,
#outId bigint OUTPUT
) AS
BEGIN
SET NOCOUNT ON;
DECLARE #ids TABLE (id bigint);
INSERT INTO [Mapping](ParentId)
OUTPUT id INTO #ids
VALUES (#parentId);
SELECT #outId = id
FROM #ids;
END;
Then call this as:
DECLARE #NewId int;
EXEC create_myNewId #parentId = 33333, #NewId OUTPUT;
SELECT #NewId;
The OUTPUT clause is the recommend way to get results from a data-modification clause. The older methods using the *_IDENTITY() functions should be obsoleted.
Stored procedures do return values. These are integers that are designed to return status information. Other information should be returned via OUTPUT parameters.
Microsoft's design intent for stored procedures is that they always return an int to describe how successful the process undertaken by the procedure was. It's not intended to return a result data, and you're free to define the bits you want to return to describe succes, partial success etc. You could abuse it to return an integer result data (count query for example) if you wanted, but it's not the design intention
Executing a select query within a stored procedure creates a result set you can read on your client if the sproc is the kind that is intended to return data
My suggestion is to use an OUTPUT parameter. Not only will it be 'easier' to use when calling the stored procedure, it will also be clearer to the person calling the stored procedure.
CREATE PROCEDURE [dbo].[create_myNewId]
(#parentId BIGINT,
#myNewId BIGINT OUTPUT)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO [Mapping] ([ParentId])
VALUES (#parentId);
SET #myNewId = SCOPE_IDENTITY();
END;
GO
You would then call your stored procedure like this:
DECLARE #myNewId BIGINT;
EXECUTE [dbo].[create_myNewId] #parentId = 0, -- bigint
#myNewId = #myNewId OUTPUT; -- bigint
SELECT [This was just inserted] = #myNewId;
For anyone who has 0 as return value from a stored procedure, check if the stored procedure executes from the right database and only one procedure exists within the given context. Output parameters wouldn't be of any use if you ever plan to access the DB with ORM and the procedure returns an object's property.

SQL. Trying to create a stored procedure on SQL, but not sure if I have the right query

Create a SQL stored procedure that parses a string into previously unknown number of fields. The inputs would be
a text string of undetermined length;
a delimiter, passed as a string;
a nullable column that, if relevant, would pass the text indicator as a single character string.
The resulting table would be entirely dependent on the string used as an input
Please help because I cannot figure this out. I know this is wrong, but I had no clue where to begin.
Here is what I have tried so far:
DECLARE #l INT, #c VARCHAR(MAX) = ''
SELECT #l = MAX(LEN(n)) FROM AdventureWOrk
DECLARE #s NVARCHAR(MAX) = '
;WITH cte AS
)
Insert INTO #Values (1, 'CGID', 'EENumber', 'EEYID', 'SSN' )
SELECT
[Value],
[Value],
Prod_Attributes.value('/Attribute[1]','varchar(MAX)') AS [CGID],
Prod_Attributes.value('/Attribute[2]','varchar(MAX)') AS [EENUMBER],
Prod_Attributes.value('/Attribute[3]','varchar(MAX') AS [EYEID],
Prod_Attributes.value('/Attribute[4]','varchar(MAX') AS [SSN]
You can create a stored procedure by using the following syntax:
CREATE PROCEDURE usp_YourProcedure
AS
BEGIN
-- Your logic
END
You would put the code you already have within the BEGIN statement.
To execute the stored procedure you can do:
EXEC usp_YourProcedure
To add parameters, simply state them after the CREATE PROCEDURE declaration.
CREATE PROCEDURE usp_YourProcedure
(
#TextField VARCHAR(MAX),
#Delimeter VARCHAR(1),
#TextIndicator CHAR(1) = NULL
)
AS
BEGIN
END
Then to execute with parameters:
EXEC usp_YourProcedure 'String literal, with commas, which will, be stripped out by the delimiter', ','
Further details are outlined at MSDN.
As an additional note, try keeping your variable names descriptive and consistent, also check the casing.
CREATE PROCEDURE <ProcedureName>
-- Add the parameters for the stored procedure here
<Param1>, <Param2> ...
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
END
GO

Unable to pull out resetSet for insert within stored procedure

I have been looking online for a few days to find a solution and
I may be asking the wrong questions.
I have the following stored proc which on insertion of a row to a db I want to get back the output int (#outResult). This is the stored proc :
USE [DB1]
GO
/****** Object: StoredProcedure [dbo].[storedProc1] Script Date: 04/12/2016 10:16:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[storedProc1]
-- Add the parameters for the stored procedure here
#inParam nvarchar(max),
#outResult int = 0 OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS
(
SELECT ID
FROM dbo.table1
WHERE Field1 = #inParam
)
Insert into [DB1].[dbo].[table1]
(
Field1
)
Values (
#inParam
)
SET #outResult = SCOPE_IDENTITY()
END
When I run the following SQL and try to retrieve the resultSet :
SELECT * FROM (EXEC storedProc1 'field1')
I get the following error:
"Incorrect syntax near the keyword 'exec'"
Maybe I am approaching this problem wrong from the first place?
I will continue to look into this and provide a solution if I find one.Any ideas?
To get the value of the output parameter you need to supply the call to the SP with an output argument. You do that by specifying the OUTPUT option on the second parameter.
DECLARE #returned_ID INT;
EXEC storedProc1 #inParam = 'field1',
#outResult = #returned_ID OUTPUT
SELECT #returned_ID
If you want to retrieve just the out parameter, then You can read it as :
DECLARE #output int
EXEC storedProc1 'field1',#output OUTPUT
SELECT #output

int is incompatible with uniqueidentifier when no int usage

I am getting this error when there is absolutely no usage of int anywhere.
I have this stored procedure
ALTER procedure [dbo].[usp_GetFileGuid] #fileType varchar(25)
as
select [id] from fileTypes where dirId = #fileType
Here id is a uniqueidentifier in fileTypes table
When I execute the following
declare #fileGuid uniqueidentifier
exec #fileGuid = usp_GetFileGuid 'accounts'
print #fileGuid
I get the following error
(1 row(s) affected)
Msg 206, Level 16, State 2, Procedure usp_GetFileGuid, Line 0
Operand type clash: int is incompatible with uniqueidentifier
Is there anything wrong with the syntax of assigning output of stored procedure to the local variable? Thank you.
You are using EXEC #fileGuid = procedure syntax which is used for retrieving return values, not resultsets. Return values are restricted to INT and should only be used to return status / error codes, not data.
What you want to do is use an OUTPUT parameter:
ALTER procedure [dbo].[usp_GetFileGuid]
#fileType varchar(25),
#id UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #id = [id] from dbo.fileTypes where dirId = #fileType;
-- if the procedure *also* needs to return this as a resultset:
SELECT [id] = #id;
END
GO
Then for usage:
declare #fileGuid uniqueidentifier;
exec dbo.usp_GetFileGuid #fileType = 'accounts', #id = #fileGuid OUTPUT;
print #fileGuid;
create procedure [dbo].[usp_GetFileGuid] #fileType varchar(25),#uuid uniqueidentifier output
as
select #uuid=[id] from fileTypes where dirId = #fileType
declare #fileGuid uniqueidentifier
exec usp_GetFileGuid 'accounts',#fileGuid output
print #fileGuid
The value returned is an int as it is the status of the execution
From CREATE PROCEDURE (Transact-SQL)
Return a status value to a calling procedure or batch to indicate
success or failure (and the reason for failure).
You are looking for an output parameter.
OUT | OUTPUT
Indicates that the parameter is an output parameter. Use
OUTPUT parameters to return values to the caller of the procedure.
text, ntext, and image parameters cannot be used as OUTPUT parameters,
unless the procedure is a CLR procedure. An output parameter can be a
cursor placeholder, unless the procedure is a CLR procedure. A
table-value data type cannot be specified as an OUTPUT parameter of a
procedure.

Failed to call a stored procedure within another stored procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[SD_Sproc_Insurance_Insert]
-- Add the parameters for the stored procedure here
(
#HCSInsuranceID bigint,
#HCSInsuranceCode varchar(10),
#HCSInsuranceName varchar(100),
#IsPPS bit,
#IsActive bit
)
AS
BEGIN TRAN InsuranceInsert
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
INSERT INTO SD_Sproc_ToGRS_Insurance(HCSInsuranceID ,HCSInsuranceCode, HCSInsuranceName, IsPPS ,IsActive)
VALUES (#HCSInsuranceID ,#HCSInsuranceCode, #HCSInsuranceName, #IsPPS, #IsActive);
COMMIT TRAN InsuranceInsert
The SD_Sproc_ToGRS_Insurance is the stored that I'll call.. I'm having a problem to call this one. Anyone suggest? That I'm doing the right path to call a stored procedure?
The above is SQL Server syntax. Use the exec command like so to call a stored procedure.
exec storedProcName #param1Name, #param2Name