Sql Procedure Not Working - sql-server

Here is my procedure:
CREATE PROCEDURE spDelManu(
#manuName VARCHAR
)
AS BEGIN
SELECT * FROM tbProducts WHERE itemManu = #manuName
END
GO
Here I try executing the procedure, but nothing shows up.
EXEC spDelManu #manuName='EVGA'
But, if I run this query it will work and I get results. Why doesn't it work with the variable created in the proc?
SELECT * FROM tbProducts WHERE itemManu = 'EVGA'

sigh, always declare explcitly the length of your varchar:
CREATE PROCEDURE spDelManu(
#manuName VARCHAR(10)
)
AS BEGIN
SELECT * FROM tbProducts WHERE itemManu = #manuName;
END
As it was, it defaulted to a length of 1

You need to set a size for varchar
CREATE PROCEDURE spDelManu(
#manuName VARCHAR
)
AS BEGIN
select #manuName
END
GO
EXEC spDelManu #manuName='EVGA'
returns: E
Bad habits to kick : declaring VARCHAR without (length) - Aaron Bertrand

Related

First stored procedure accepts parameters - then passes them to 2nd stored procedure whose results are returned. How?

I have a stored procedure A on server 1 that takes 2 parameters from the user, and then using a linked server (ew), pulls in the results (a table) from server 2.
ALTER PROCEDURE [DW].[StoredProcA]
#InvFromDate date OUTPUT,
#InvToDate date OUTPUT
AS
WITH CTE_Labor AS
(
SELECT blabla
FROM LinkedServer.Database.schema.table
<lots more ctes, etc.>
For performance, I'd like to instead have a stored procedure A still accept the 2 parameters, but then pass them on to stored procedure B that sits on Server 2, and return those results back to the user.
Say - I can put the stored procedure on server 2, and call it from Server 1
DECLARE #return_value int
EXEC #return_value = [LinkedServer].[DB].[Schema].[StoredProcB]
#InvFromDate = '2022-10-01',
#InvToDate = '2022-10-31'
That works.
But I'm not clear on the syntax to do the above, but have those 2 parameters be entered by the user in stored procedure 1.
Clearly this attempt is wrong:
ALTER PROCEDURE dbo.StoredProc1
#InvFromDate DATE,
#InvToDate DATE
AS
BEGIN
DECLARE #return_value int;
EXEC #return_value = [LinkedServer].[DB].[Schema].[StoredProcB]
#InvFromDate = #InvFromDate,
#InvToDate = #InvToDate;
RETURN #return_value;
END
Edit: Maybe this attempt isn't wrong.
It works when I right click and run the stored procedure, returning both the desired table and Return Value = 0. It just doesn't work when I point our front-end GUI at it. But that might not be a question for here.
Since you are already using a linked server you could utilise this openquery approach Insert results of a stored procedure into a temporary table
Noting the following:
OPENQUERY/ linked servers are generally bad but I'm sure you're all over this
parameter string concatenation is bad
Your wrapper proc has output parameters but I don't see any reason for it... so I've removed them. See if it makes a difference.
--
ALTER PROCEDURE [DW].[StoredProcA]
#InvFromDate date,
#InvToDate date
AS
DECLARE #sql VARCHAR(4000)
SET #sql = 'EXEC [DB].[Schema].[StoredProcB] #InvFromDate = ''' + FORMAT(#InvFromDate + 'yyyy-MM-dd') + ''',#InvToDate = ''' + FORMAT(#InvToDate,'yyy-MM-dd') + ''''
PRINT(#sql) -- for degbugging cause this never works first time
SELECT *
INTO #tmpTable
FROM OPENQUERY([LinkedServer], #SQL)
SELECT * FROM #tmpTable
Got it.
1.) For this method, have to go into the Linked Server, and set [Enable Promotion of Distribution Transaction] = FALSE.
2.) Syntax
Alter proc [dbo].[999_Test]
#InvFromDate date
,#InvToDate date
as
IF OBJECT_ID('tempdb..#tmpbus') IS NOT NULL drop table #tmpbus;
CREATE TABLE #tmpBus
(
Column 1 (datatype),
Column 2 (datatype),
etc. )
INSERT INTO #tmpBus
EXEC [LinkedServer].[DB].Schema.[StoredProcInLinkedServerO]
#InvFromDate,
#InvToDate;
select *
from #tmpBus
GO

how to use declare variable in select query in stored procedure using sql server

Hello I want to concate two things one is string and other is int variable. Now, these thing I want to store in one variable and use that variable in select query as a into type to create a temptable in stored procedure using sql server.
Here is my query
USE [FlightExamSoftware]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- For Storing Question in Temp table
-- EXEC [GetQuestionListPerSubjectRatioWise] 1,11
ALTER PROCEDURE [dbo].[GetQuestionListPerSubjectRatioWise]
#SubjectID INT,
#NumberOfQue INT,
#UserID int
AS
BEGIN
DECLARE #strQuery VARCHAR(MAX);
DECLARE #PerChapQue INT;
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID;
SELECT #PerChapQue = COUNT(appQueID)/#NumberOfQue FROM tblQuestion WHERE appQueSubID=#SubjectID
SELECT COUNT(appQueID)/#PerChapQue ChapwiseQue
,CASE WHEN COUNT(appQueID)>=#PerChapQue THEN COUNT(appQueID)/#PerChapQue ELSE 1 END ChapWiseQuePlusOne
,appQueChapID into #tempTable
FROM tblQuestion
WHERE appQueSubID=#SubjectID
GROUP BY appQueChapID
END
Now, I am talking about these line
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID;
In these line two things are concate one is string and other is int. And store in varchar variable.
And use in following select query i.e.
SELECT COUNT(appQueID)/#PerChapQue ChapwiseQue
,CASE WHEN COUNT(appQueID)>=#PerChapQue THEN COUNT(appQueID)/#PerChapQue ELSE 1 END ChapWiseQuePlusOne
,appQueChapID into #tempTable
FROM tblQuestion
WHERE appQueSubID=#SubjectID
GROUP BY appQueChapID
END
Now, in these query I want to create a temptable named #tempTable.
But, in these line it showing error i.e. Incorrect syntax near '#tempTable'.
Confuse that where is the syntax is wrong.
Thank You.
There are a number of things wrong with your code.
When concatenating an int to a string, you must first cast the int to varchar. Otherwise, SQL Server will try to implicitly convert the string to int, that will result with an error.
So this: DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + #UserID; should become this:
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + CAST(#UserID AS VARCHAR(11)); (you need 11 chars to be able to fit the minimum value of int: -2,147,483,648)
You can't use select...into with a table variable.
You can only use it for actual tables (temporary or regular).
your #tempTable isn't even a table variable (not that it will help with a select...into).
Even if you would use select...into the correct way, unless you are going to use a global temporary table (and that doesn't come without it's risks), Unless your stored procedure uses this temporary table later on, it will be useless, since temporary tables are bound to scope.
Taking all of that into consideration I'm not sure what output you are actually looking for. If you could edit your question to include the desired output of your stored procedure as well as some sample data as DDL+DML, it would be easier to help you write better code.
Hope this Dynamic Query helps you:
Try like this:
USE [FlightExamSoftware]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- For Storing Question in Temp table
-- EXEC [GetQuestionListPerSubjectRatioWise] 1,11
ALTER PROCEDURE [dbo].[GetQuestionListPerSubjectRatioWise]
#SubjectID INT,
#NumberOfQue INT,
#UserID int
AS
BEGIN
DECLARE #strQuery VARCHAR(MAX);
DECLARE #PerChapQue INT;
DECLARE #tempTable VARCHAR(MAX) = 'tempTestUser' + CAST(#UserID AS VARCHAR);
SELECT #PerChapQue = COUNT(appQueID)/#NumberOfQue FROM tblQuestion WHERE appQueSubID=#SubjectID
SET #strQuery='
SELECT COUNT(appQueID)/'+CAST(#PerChapQue AS VARCHAR)+' ChapwiseQue
,CASE WHEN COUNT(appQueID)>='+CAST(#PerChapQue AS VARCHAR)+' THEN COUNT(appQueID)/'+CAST(#PerChapQue AS VARCHAR)+' ELSE 1 END ChapWiseQuePlusOne
,appQueChapID
INTO '+#tempTable+'
FROM tblQuestion
WHERE appQueSubID='+CAST(#SubjectID AS VARCHAR)+'
GROUP BY appQueChapID
/*.................................
And you have to use the temp table inside the String only
.................................*/
'
EXEC (#strQuery)
END

SqlException: Procedure or function expects parameter which was not supplied SSMS

I am sure the solution is something super simple that I am missing but I keep getting a
SqlException: Procedure or function expects parameter which was not supplied
error. I am not a SQL wizard but to me the parameter looks okay. I did change the parameter and was not receiving this error but then when I consistently started receiving it I restored the stored procedure to the original version that I knew for a fact was fine but still receive it.
I tried executing the stored procedure like this
EXECUTE [dbo].[BHS_CloseCnt_Print_PackList] #palletid = '562992'
with a variable filled in. This stored procedure calls a function that determines the status of an order, if the variable I plug in and check with this method meets the criteria for the function I get an expected return.
If the container does not yet meet the function criteria, I get a null which I believe is okay.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[BHS_CloseCnt_Print_PackList]
(#PalletId numeric)
AS
BEGIN
Declare #PO as nvarchar(50)
Declare #Internal_Shipment_Num as numeric
Declare #Internal_Shipment_Line_Num as numeric
select top 1
#Internal_Shipment_Num = sc.INTERNAL_SHIPMENT_NUM,
#Internal_Shipment_Line_Num = sc.INTERNAL_SHIPMENT_LINE_NUM
from
SHIPPING_CONTAINER sc
where
INTERNAL_CONTAINER_NUM = #PalletId
or PARENT = #PalletId
and INTERNAL_SHIPMENT_LINE_NUM is not null
select #PO = dbo.fn_BHS_AllPOPLTS_CLOSED(#PalletId, #Internal_Shipment_Num, #Internal_Shipment_Line_Num)
print #PO
if #PO is not null
Begin
select #PalletId 'INTERNAL_CONTAINER_NUM', '60' 'DOCUMENT_TYPE'
End
End
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_BHS_AllPOPLTS_CLOSED]
(#palletId numeric,
#Internal_Shipment_Num numeric,
#Internal_Shipment_Line_Num numeric)
RETURNS nvarchar(50)
AS
BEGIN
Declare #PO nvarchar(50)
Declare #OPENPO nvarchar(50)
Declare #IntShip as numeric
select #PO = isnull(sd.CUSTOMER_PO, 'FEIT')
from SHIPMENT_DETAIL sd
where sd.INTERNAL_SHIPMENT_LINE_NUM = #Internal_Shipment_Line_Num
and sd.internal_shipment_num = #Internal_Shipment_Num
select #OPENPO = isnull(sd.CUSTOMER_PO, '')
from shipping_container sc
join SHIPMENT_DETAIL sd on sd.INTERNAL_SHIPMENT_LINE_NUM = sc.INTERNAL_SHIPMENT_LINE_NUM
where sd.CUSTOMER_PO = #PO and sc.INTERNAL_SHIPMENT_NUM = #Internal_Shipment_Num
and sc.status < 600
if(isnull(#OPENPO, '') != '')
Begin
set #PO = null
End
return #PO
End
The stored procedure looks to have stored the cache from the previous edit I did although a known working version was restored.
Resolution for this was to run DBCC FREEPROCCACHE to clear the stored procedure cache and I was able to execute as expected.
Thanks Nemanja Perovic!

SQL Server stored procedure always returning 0

I was asked to calculate a percentage of a number through a stored procedure in SQL Server, but for some reason no matter what the parameters are, I always get a 0.
My question is what is happening here?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE pCalcular
#PrecioTotal INT,
#cantidad INT
AS
BEGIN
PRINT ' Calculando ' + CAST (#PrecioTotal * #cantidad AS VARCHAR(40))
SELECT #cantidad = #PrecioTotal * #cantidad
END
I'm calling the procedure the following way, I'm not sure what the problem is.
DECLARE #abc AS INT
EXEC #abc = pCalcular 70, .1
PRINT #abc
You're only setting the value #cantidad in the procedure. You just need to SELECT that value from the PROC. Try just having;
SELECT #PrecioTotal * #cantidad
Also, take a look at other ways of returning data from procedures like OUTPUT parameters.
EDIT:
Your procedure should look like this;
ALTER PROCEDURE pCalcular
#PrecioTotal INT,
#cantidad INT
AS
BEGIN
PRINT ' Calculando ' + CAST (#PrecioTotal * #cantidad AS VARCHAR(40))
SELECT #PrecioTotal * #cantidad
END

SP_ExecuteSQL Generic stored_procedure call without output parameters, but catching the output

I'm scratching my head hard on this pb and I would like some help to figure out some solution.
Inside some TSQL programmable object (a stored procedure or a query in Management Studio)
I have a parameter containing the name of a stored procedure + the required argument for these stored procedures (for exemple it's between the brackets [])
Sample of #SPToCall
EX1 : [sp_ChooseTypeOfResult 'Water type']
EX2 : [sp_ChooseTypeOfXMLResult 'TABLE type', 'NODE XML']
EX3 : [sp_GetSomeResult]
I can't change thoses stored procedures (and I don't have a nice output param to cache, as I would need to change the stored procedure definition)
All these stored procedures 'return' a 'select' of 1 record the same datatype ie: NVARCHAR. Unfortunately there is no output param in those stored procedures definition (it would have been too easy otherwise :D)
So I'm working on something like this but I can't find anything working
DECLARE #myFinalVarFilledWithCachedOutput NVARCHAR(MAX);
DECLARE #SPToCall NVARCHAR(MAX) = N'sp_ChooseTypeOfXMLResult ''TABLE type'', ''NODE XML'';'
DECLARE #paramsDefintion = N'#CatchedOutput NVARCHAR(MAX) OUTPUT'
exec SP_executeSQL #SPToCall , #paramsDefinitions, #CatchedOutput = #myFinalVarFilledWithCachedOutput OUTPUT
-- my goal is to get something inside #myFinalVarFilledWithCachedOutput
Select #myFinalVarFilledWithCachedOutput
Any ideas ?
Here's an example of the syntax to take output of stored procedure that returns a selected value and pass that output to a table variable.
CREATE PROCEDURE tester
AS
BEGIN
DECLARE #var VARCHAR(10)
SET #var = 'beef'
SELECT #var
END
GO
DECLARE #outputtab TABLE ( varfield VARCHAR(100) )
INSERT #outputtab
( varfield )
EXEC tester
GO
SELECT *
FROM #outputtab
From there if you want to get it into a varchar variable:
DECLARE #outputvar VARCHAR(100)
SET #outputvar = ( SELECT TOP 1
*
FROM #outputtab
)

Resources