I want to add or update with the code below. I get the following error. How should I edit this code?
Must declare the scalar variable "#UyeID".
Incorrect syntax near the keyword 'ELSE'.
My code:
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE
(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE Insert_BcgTarihleri
(#tblBcgTarihleri BcgTarihiType READONLY)
AS
BEGIN
IF EXISTS (SELECT 1 FROM BcgTarihleri
WHERE UyeID = #UyeID AND BcgTarihi = #BcgTarihi)
BEGIN
UPDATE BcgTarihleri
SET UyeID = #UyeID, BcgTarihi = #BcgTarihi
WHERE UyeID = #UyeID
END
ELSE
BEGIN
INSERT INTO BcgTarihleri
VALUES (#UyeID, #BcgTarihi)
END
END
I also want to ask the question in this way. The code below works but I can only add.How can this update if exist data?
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE Insert_BcgTarihleri
(
#tblBcgTarihleri BcgTarihiType READONLY
)
AS
BEGIN
INSERT into BcgTarihleri (UyeID,BcgTarihi)
SELECT UyeID, BcgTarihi FROM #tblBcgTarihleri;
END
#Boris Makhlin, #Dale K Thank you for your help I solved my problem with the code below
CREATE TYPE [dbo].[BcgTarihiType] AS TABLE(
[UyeID] int NOT NULL,
[BcgTarihi] [nvarchar](30) NULL
)
GO
CREATE PROCEDURE [dbo].[Update_BcgTarihleri]
#tblBcgTarihleri BcgTarihiType READONLY
AS
BEGIN
SET NOCOUNT ON;
MERGE INTO BcgTarihleri b1
USING #tblBcgTarihleri b2
ON b1.UyeID = b2.UyeID AND b1.BcgTarihi = b2.BcgTarihi
WHEN MATCHED THEN
UPDATE SET b1.UyeID = b2.UyeID
,b1.BcgTarihi = b2.BcgTarihi
WHEN NOT MATCHED THEN
INSERT VALUES(b2.UyeID, b2.BcgTarihi);
END
Related
I have a stored procedure I would like to use its result in a Web API (C#).
I must miss something since I'm getting no result nor in Complex Types (in EF model) neither in Functions Imports (I can see the stored procedure in Functions Imports but it does not return any value, as expected).
This is my stored procedure (I have erased some non-important data in order to make it shorter)
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
#main_id BIGINT,
#id_ze_mish BIGINT,
#id_nof BIGINT,
#loggedInUser VARCHAR(20)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION [TransactionUniteSingles]
OPEN SYMMETRIC KEY io_key DECRYPTION BY CERTIFICATE chn_cert
-- Step 1
UPDATE [dbo].[t1]
SET deleted = 1,
WHERE id_nof = #id_nof
AND id_ze = #id_ze_mish
-- Step 2
UPDATE [dbo].[t_no_nir]
SET update_stamp = GETDATE(),
[user_name] = #loggedInUser
WHERE id_nof = #id_nof
AND ms_zehut_mazmin = #id_ze_mish
-- Step 3
CREATE TABLE #mainPrice
(
id INT,
fName VARCHAR(20),
lName VARCHAR(20)
)
INSERT INTO #mainPrice
EXEC [dbo].[io_sp_get_some_data_foo] #id
IF(EXISTS(select * from #mainPrice))
BEGIN
DECLARE #totalAmount INT;
SELECT #totalAmount = (main_price + price_tip + price_visa)
FROM #mainPrice
DROP TABLE #mainPrice
UPDATE [dbo].[t_4]
SET amount = #totalAmount,
update_stamp = GETDATE(),
[user_name] = #loggedInUser
WHERE id_nof = #id_nof
AND id = #main_id
CLOSE ALL SYMMETRIC KEYS
COMMIT TRANSACTION [TransactionUniteSingles]
SELECT CAST(1 as BIT) as 'Status', 'Succeeded' as 'ReturnMessage'
END
ELSE
BEGIN
SELECT CAST(0 as BIT) as 'Status', 'ADMIN - Unite Singles as 'ReturnMessage'
END
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION [TransactionUniteSingles]
SELECT CAST(0 as BIT) as 'Status', 'ADMIN - Unite Singles' as 'ReturnMessage'
END CATCH
END
Please note - when running the stored procedure as standalone, it works perfectly and return what expected.
Check what happens when you call your procedure with NULL input parameters. If the result is not a table then EF will not generate the complex result.
Try following:
-- declare table at SP begin
DECLARE #ResultTable TABLE(
Status BIT NOT NULL,
ResultMessage NVARCHAR(50) NOT NULL
)
-- insert data where you need
INSERT INTO #ResultTable
(
Status,
ResultMessage
)
VALUES
( NULL, -- Status - bit
N'' -- ResultMessage - nvarchar(50)
)
-- at SP end select result from table
SELECT * FROM #ResultTable
I found out that my problem is with my temp table.
when using SET FMTONLY OFF at the top of my SP or above the temp table(#mainPrice in my case) then everything works like a charm and suddenly the Complex Types shows my SP.
Another solution is using a variable table: DECLARE TABLE #mainPrice.
Both do the work.
I'll be happy to know why it happens and why C# refused to get a temp table as part of my SP , but at the moment I found the solution needed.
I am not getting what I am doing wrong here. From the update segment, I am getting this error:
Must declare the scalar variable "#OrderTestTVP".
Here is my table-valued parameter type
CREATE TYPE [dbo].[TVP_OrderTest] AS TABLE(
[OrderTestId] [int] NULL,
[OrderId] [int] NOT NULL,
[TestCode] [varchar](10) NOT NULL
)
GO
ALTER PROCEDURE [dbo].[TVP_Save_OrderTest]
#OrderTestTVP TVP_OrderTest READONLY
AS
BEGIN
BEGIN TRY
DECLARE #TableOfIdentities TABLE (IdentValue BIGINT, TestCode varchar(10) )
INSERT INTO OrderTest
(
OrderId
,TestCode
)
OUTPUT Inserted.OrderTestId,inserted.TestCode
INTO #TableOfIdentities(IdentValue,TestCode)
SELECT OrderId
,TestCode
FROM #OrderTestTVP
WHERE OrdertestID = 0
UPDATE
OrderTest
SET
OrderId = #OrderTestTVP.OrderId,
TestCode = #OrderTestTVP.TestCode
FROM OrderTest INNER JOIN #OrderTestTVP
ON OrderTest.OrderTestId = #OrderTestTVP.OrderTestId
SELECT * FROM #TableOfIdentities
END TRY
BEGIN CATCH
exec error_catch
END CATCH
END
I'd say you have to use a table alias for the join operation:
UPDATE
OrderTest
SET
OrderId = o.OrderId,
TestCode = o.TestCode
FROM OrderTest INNER JOIN #OrderTestTVP o
ON OrderTest.OrderTestId = o.OrderTestId
I have no SQL at hand right now to try but if I recall correctly, table variables need aliases if used in expressions.
I am trying to trigger a report to run with "select all" checked for a field FiscalYearId, which is a string type. I can successfully pass one string such as "2" and the report will find it. However, when I try to pass "select all" or "2,3,4", the multi-check field does not pick up on this.
Here is part of the stored procedure from the report:
ALTER PROCEDURE [dbo].[...]
#FiscalYearId varchar (100) = null ,
...
select ...
where ...
and (#FiscalYearID IS NULL OR p.FiscalYearId IN (SELECT * FROM SPLIT(#FiscalYearID, ',')))
my c# code which triggers the report to pop up in a radwindow is:
`string years = "2,3,4";
newWindow.NavigateUrl = "../Reporting/SingleReport.aspx?Report=AdHocSourcingReport&VendorID="
+ vendorId + "&VendorReport=true" + "&FiscalYearId="+years;`
Currently, the vendorId string and VendorReport boolean pull through successfully, it is the string separated by commas that is not populating when the report is run. I initially tried to send a "select all", which is what I want.. Any help is greatly appreciated!!
This is how I've handled splitting comma delimited strings in the past:
CREATE FUNCTION
[dbo].[GetItemTable]
(
#Items VARCHAR(1000)
)
RETURNS
#ItemTable TABLE
(
RowID INT IDENTITY(1,1) PRIMARY KEY,
item VARCHAR(30)
)
AS
BEGIN
DECLARE #ProcessItems VARCHAR(1000)
DECLARE #CurrentItem VARCHAR(30)
SET #ProcessItems = REPLACE(#Items, '''', '')
IF SUBSTRING(#ProcessItems, LEN(#ProcessItems), 1) ','
SET #ProcessItems = #ProcessItems + ','
WHILE CHARINDEX(',', #ProcessItems) > 0
BEGIN
SET #CurrentItem = LTRIM(CAST(SUBSTRING(#ProcessItems, 0, CHARINDEX(',', #ProcessItems)) AS VARCHAR(30)))
INSERT INTO
#ItemTable
(
item
)
VALUES
(
#CurrentItem
)
SET #ProcessItems = SUBSTRING(#ProcessItems, CHARINDEX(',', #ProcessItems) + 1, LEN(#ProcessItems))
END -- While Schedule
RETURN
END
Obviously, you can change the current item size to whatever you happen to need it to be.
Then just use it like this:
WHERE (p.FiscalYearId IN(SELECT item FROM dbo.GetItemTable(#FiscalYearID)))
I remember doing something similar couple years ago and having same kinds of problem with the list.
Can you try this...
ALTER PROCEDURE [dbo].[...] #FiscalYearId varchar (100) = null ,
... select... where... and
(#FiscalYearID IS NULL OR p.FiscalYearId IN (#FiscalYearID))
Also, if you are sending "Select all" string, you might need to have a condition in your procedure to check that and change the query to "Select id from fiscalyeartable"
I want to create a procedure that inserts into a table and returns it's primary key.
The primary key of table is uniqueidentyfire and it's guid is true
This is the stored procedure:
ALTER PROCEDURE [dbo].[pr_Tbl_Erae_Insert]
#sfk_Dars varchar(20),
#sfk_Ostad varchar(20),
#byfk_Gerayesh tinyint,
#ifk_term int,
#guidErae_ID uniqueidentifier,
#byGroup_Number tinyint,
AS
-- INSERT a new row in the table.
INSERT [dbo].[Tbl_Erae]
(
[fk_Dars],
[fk_Ostad],
[fk_Gerayesh],
[fk_term],
[Erae_ID],
[Group_Number]
)
VALUES
(
#sfk_Dars,
#sfk_Ostad,
#byfk_Gerayesh,
#ifk_term,
ISNULL(#guidErae_ID, (newid())),
#byGroup_Number
)
I need to return Erae_Id when it inserted into table how can I do that?
Can I use from output variables? How?
There is an OUTPUT clause available, depending on your version; however, in this case it is probably easier (since you only have one row) to handle this separately:
IF #guidErae_ID IS NULL SET #guidErae_ID = NEWID()
then use #guidErae_ID "as is" in the INSERT (no ISNULL), and then either end with:
SELECT #guidErae_ID
and use var result = (Guid)command.ExecuteScalar(), or mark #guidErae_ID as OUTPUT in the parameter definition, and query it after calling command.ExecuteNonQuery().
If you need to return the value in the #guidErae_ID parameter that you've included, then you need to mark the parameter for output, and then set it in the proc:
ALTER PROCEDURE [dbo].[pr_Tbl_Erae_Insert]
#sfk_Dars varchar(20),
#sfk_Ostad varchar(20),
#byfk_Gerayesh tinyint,
#ifk_term int,
#guidErae_ID uniqueidentifier output,
#byGroup_Number tinyint,
AS
If #guidErae_ID is null set #guidErae_ID = newid()
-- INSERT a new row in the table.
INSERT [dbo].[Tbl_Erae]
(
[fk_Dars],
[fk_Ostad],
[fk_Gerayesh],
[fk_term],
[Erae_ID],
[Group_Number]
)
VALUES
(
#sfk_Dars,
#sfk_Ostad,
#byfk_Gerayesh,
#ifk_term,
#guidErae_ID,
#byGroup_Number
)
at the end of your stored procedure just add one more line like this
return select Erae_Id WHERE [fk_Dars] = #sfk_Dars
AND
[fk_Ostad] = #sfk_Ostad
AND
[fk_Gerayesh] = #byfk_Gerayesh
AND
[fk_term] = #ifk_term
AND
[Group_Number] = #byGroup_Number
Is it possible to send a list of IDs to a stored procedure from c#?
UPDATE Germs
SET Mutated = ~Mutated
WHERE (GermID IN (ids))
This may be a dirty hack, but you can create a temp table and then join to it from within your stored procedure (assuming they are accessed during the same connection). For example:
CREATE TABLE #ids (id int)
INSERT INTO #ids VALUES ('123') -- your C# code would generate all of the inserts
-- From within your stored procedure...
UPDATE g
SET Mutated = ~Mutated
FROM Germs g
JOIN #ids i ON g.GermID = i.id
You could try what i have made do with:-
Create a function called Split_String
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE FUNCTION [dbo].[Split_String]
(
#MyString varchar(5000)
)
RETURNS #Results TABLE
(
Value varchar(1000)
)
AS
BEGIN
DECLARE #Pos int
DECLARE #StrLen int
DECLARE #MyLen int
DECLARE #MyVal varchar
SET #pos = 1
SET #MyLen = 1
WHILE #MyString <> ''
BEGIN
SET #MyLen = charindex(',',#MyString)
IF #MyLen = 0 SET #MyLen = Len(#MyString)
INSERT #Results SELECT replace(substring(#MyString, #pos, #MyLen),',','')
SET #MyString = SUBSTRING(#MyString,#MyLen+1,len(#MyString))
END
RETURN
END
Then when you use IN() use in the following fashion with a comma separated string:-
SELECT * FROM [youDataBase].[dbo].[Split_String] (<#MyString, varchar(5000),>)
According to This article, you could try the Table Value Parameter.
Yep, you can use a chunk of XML to build your list of ID's. Then you can use OPENXML and select from that record set.
Look up OPENXML, sp_preparexmldocument, sp_removexmldocument