Insert data from XML file into existing SQL Server table - sql-server-2014

I need to insert data from XML file into existing SQL SERVER table. I have modified following code to INSERT INTO but its not working. I don't want to delete or create new table in this statement
DECLARE #x xml
SELECT #x=P
FROM OPENROWSET (BULK 'D:\Course Instance Marketing Data From Drupal\instance_marketing.xml', SINGLE_BLOB ) AS COURSE_INSTANCE(P)
DECLARE #hdoc int
EXEC sp_xml_preparedocument #hdoc OUTPUT, #x
SELECT *
INTO RCMI_MARKETING_SYNC
FROM OPENXML(#hdoc,'/response/item', 2)
WITH(
CourseInstanceKey int '#key',
idRCMI_MARKETING_SYNC int '#key' ,
title varchar(3000),
course_code varchar(3000),
market_area varchar(3000),
ssa varchar(3000),
school_owning varchar(3000),
overview varchar(3000),
entry_requirements varchar(3000),
teaching_methods varchar(3000),
modules_and_assessment varchar(3000),
career_options_progres varchar(3000),
equipment_needed_costs varchar(3000),
work_placement_field_trips varchar(3000)
)
EXEC sp_xml_removedocument #hdoc
Error
Msg 2714, Level 16, State 6, Line 10
There is already an object named 'RCMI_MARKETING_SYNC' in the database.
I don't want to delete existing table

First of all:
Your approach with FROM OPENXML with the corresponding SPs to prepare and remove the document is outdated. You should use the appropriate XML methods
If you need help with this, please start a new question with a (reduced) example of your XML and place a link here.
Your question is not related to xml actually...
Your statement with SELECT .. INTO tbl will create this table physically. If this table exists already, you'll get an error.
Inserts into an existing table must be written slightly differently:
INSERT INTO RCMI_MARKETING_SYNC(col1, col2, col3,...) --place the actual column names here
SELECT col1, col2, col3, ... FROM SomeWhere --replace this by your XML-shredding query.

Found answer
DECLARE #x xml
SELECT #x=P
FROM OPENROWSET (BULK 'D:\Course Instance Marketing Data From Drupal\instance_marketing.xml', SINGLE_BLOB ) AS COURSE_INSTANCE(P)
DECLARE #hdoc int
EXEC sp_xml_preparedocument #hdoc OUTPUT, #x
INSERT INTO RCMI_MARKETING_SYNC
SELECT *
FROM OPENXML(#hdoc,'/response/item', 2)
WITH(
CourseInstanceKey int '#key',
idRCMI_MARKETING_SYNC int '#key' ,
title varchar(3000),
course_code varchar(3000),
market_area varchar(3000),
ssa varchar(3000),
school_owning varchar(3000),
overview varchar(3000),
entry_requirements varchar(3000),
teaching_methods varchar(3000),
modules_and_assessment varchar(3000),
career_options_progres varchar(3000),
equipment_needed_costs varchar(3000),
work_placement_field_trips varchar(3000)
)
EXEC sp_xml_removedocument #hdoc

Related

SQL on US Census - Null values return

I am trying to get data from the US Census on SQL Server Studio for analysis (trade data at port level). I have downloaded a JSON file for now from their API (ideally, I will do a call from SQL studio later). I then read the file with OPEN ROW SET and OPEN JSON, I can read the file but when I add the with clause to get the column, I only get NULL values.
Declare #JSON varchar(max)
SELECT #JSON=BulkColumn
FROM OPENROWSET (BULK 'C:\Users\amartinez\US.json', SINGLE_CLOB) j
SELECT * FROM OPENJSON (#JSON)
WITH (
[CTY_CODE] varchar(max) '$.CTY_CODE',
[CTY_NAME] varchar(max) '$.CTY_NAME',
[I_ENDUSE] varchar(max) '$.I_ENDUSE',
[I_ENDUSE_LDESC] varchar(max) '$.I_ENDUSE_LDESC',
[GEN_VAL_MO] int '$.GEN_VAL_MO',
[CON_VAL_MO] int '$.CON_VAL_MO',
[time] varchar(max) '$.time'
) as tradeF;
Input file
Please try the following solution.
Your JSON is a JSON array, so it needs a slightly different syntax.
SQL
DECLARE #JSON VARCHAR(MAX);
SELECT #JSON=BulkColumn
FROM OPENROWSET (BULK 'C:\Users\amartinez\US.json', SINGLE_CLOB) j;
SELECT tradeF.*
FROM OPENJSON (#JSON)
WITH (
[CTY_CODE] varchar(max) '$[0]',
[CTY_NAME] varchar(max) '$[1]',
[I_ENDUSE] varchar(max) '$[2]',
[I_ENDUSE_LDESC] varchar(max) '$[3]',
[GEN_VAL_MO] varchar(max) '$[4]',
[CON_VAL_MO] varchar(max) '$[5]',
[time] varchar(max) '$[6]'
) as tradeF;

Trigger a stored procedure #2 within another stored procedure #1 based on input from the first stored procedure #1

I need to create a stored procedure which triggers another stored procedure based on what the first stored procedure ingests.
I have a master table called 'Data_Table' which ingests JSON strings. Within the JSON string is another JSON string which is the data of a separate table.
My objective is: when the master table ingests this data, based on the 'data_set_id', it directs the JSON embedded within the table to automatically be ingested into another table via a separate stored procedure already set up. For instance:
CREATE PROCEDURE INSERT_DATA_TABLE_JSON (
#JsonData NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #err int
INSERT INTO Data_Table (
submission_id,
data_set_id,
data_string
)
SELECT *
FROM OPENJSON (#JsonData, N'$') WITH (
submission_id varchar(20) N'$.submission_id',
data_set_id varchar(20) N'$.data_set_id',
data_string varchar(1000) N'$.data_string'
)
SELECT #err = ##ERROR
RETURN (#err)
END
I would then execute this by running the following query:
DECLARE #RC int
DECLARE #JsonData nvarchar(max)
SET #JsonData = N'[{"submission_id":"1","data_set_id":"1","data_string":"[{\"student_id\":1,\"full_name\":\"John Smith\",\"submission_id\":\"1\",\"data_set_id\":\"1\"}]"}]
for json path'
EXECUTE #RC = [dbo].[INSERT_DATA_TABLE_JSON] #JsonData
IF #RC = 0 PRINT 'OK'
ELSE PRINT 'Error'
As you can see, within the 'data_string' column of the Data_Table, we have another JSON. This data_set_id =1 just means that this data is related to a specific table, in this case my Student table which has the following stored procedure:
CREATE PROCEDURE INSERT_STUDENTS_JSON (
#JsonData NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #err int
INSERT INTO Students (
student_id,
full_name,
submission_id,
data_set_id
)
SELECT *
FROM OPENJSON (#JsonData, N'$') WITH (
student_id varchar(20) N'$.student_id',
full_name varchar(20) N'$.full_name',
submission_id varchar(20) N'$.submission_id',
data_set_id varchar(20) N'$.data_set_id'
)
SELECT #err = ##ERROR
RETURN (#err)
END
How do I automatically, allow the first stored procedure, to read the contents of the embedded JSON or otherwise, and then for it to know that it has to use that data to fill in the corresponding Students table.
Here is the JSON string just in case:
[{"submission_id":"1","data_set_id":"1","data_string":"[{\"student_id\":1,\"full_name\":\"John Smith\",\"submission_id\":\"1\",\"data_set_id\":\"1\"}]"}]
I have a second table called Lecturers which I've assigned with data_set_id = 2, so when the embedded JSON has data_set_id = 2, it directs it to the lecturers table.

Save a SQL query result to an XML file without SSIS or xp_cmdshell

I've been searching for days on a solution for the problem I have.
I have an SQL server query that produces some output I require in XML so this is the query:
SELECT FinishCode, reason, COUNT(reason) as Numbers
FROM [I3_Dialer].[dbo].[I3_UKPIPELINEWORKFLOW_CH0]
WHERE callplacedtime > (select cast(convert(varchar(10), getdate(), 110) as datetime)) and reason = 'Success'
GROUP BY reason, finishcode
ORDER BY Numbers
FOR XML PATH('FinishCode'), ROOT('UK_Products_Pipeline');
That output produces an XML, but I need it stored as a file and to run as a job every xx minutes.
All solutions I found sofar use BCP with xp_cmdshell or SSIS. The only thing I have found that is available on the SQL server is BCP (to my surprise) and the server has not enough resources to install SSIS, neither does the SQL admin want to enable or install additional software.
I tried to run a Job with this but the file it generates contains to much additional information that messes up the XML.
Any suggestions welcome as I'm a novice when it comes to SQL.
After long digging I found a solution to my problem:
I created a stored procedure like this:
USE [DATABASE NAME]
GO
/****** Object: StoredProcedure [dbo].[asp_Write_String_To_File] Script Date: 11/21/2013 09:33:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [PROCEDUER NAME]
(
#String Varchar(max), --8000 in SQL Server 2000
#Path VARCHAR(255),
#Filename VARCHAR(100)
)
AS
DECLARE #objFileSystem int,
#objTextStream int,
#objErrorObject int,
#strErrorMessage Varchar(1000),
#Command varchar(1000),
#hr int,
#fileAndPath varchar(80)
set nocount on
select #strErrorMessage='opening the File System Object'
EXECUTE #hr = sp_OACreate 'Scripting.FileSystemObject' , #objFileSystem OUT
Select #FileAndPath=#path+'\'+#filename
if #HR=0 Select #objErrorObject=#objFileSystem , #strErrorMessage='Creating file "'+#FileAndPath+'"'
if #HR=0 execute #hr = sp_OAMethod #objFileSystem , 'CreateTextFile' , #objTextStream OUT, #FileAndPath,2,True
if #HR=0 Select #objErrorObject=#objTextStream, #strErrorMessage='writing to the file "'+#FileAndPath+'"'
if #HR=0 execute #hr = sp_OAMethod #objTextStream, 'Write', Null, #String
if #HR=0 Select #objErrorObject=#objTextStream, #strErrorMessage='closing the file "'+#FileAndPath+'"'
if #HR=0 execute #hr = sp_OAMethod #objTextStream, 'Close'
if #hr<>0
begin
Declare
#Source varchar(255),
#Description Varchar(255),
#Helpfile Varchar(255),
#HelpID int
EXECUTE sp_OAGetErrorInfo #objErrorObject, #source output,#Description output,#Helpfile output,#HelpID output
Select #strErrorMessage='Error whilst ' +coalesce(#strErrorMessage,'doing something') +', '+coalesce(#Description,'')
raiserror (#strErrorMessage,16,1)
end
EXECUTE sp_OADestroy #objTextStream
EXECUTE sp_OADestroy #objTextStream
then in the query I call the stored procedure like this:
USE [DATABASE NAME]
declare #xml nvarchar(max)
declare #FilePath nvarchar(255)
declare #FileName nvarchar(255)
set #FilePath = '[Path to store file]' -- Location to store the file
set #FileName = '[File Name to store].xml' -- This is the XML filename
BEGIN
set #xml =
(
SELECT ( -- Add This
SELECT FinishCode, Reason, COUNT(*) AS Numbers
FROM [DATABASE] ch WITH (NOLOCK)
WHERE [Condition 1]
AND [Condition 2]
GROUP BY Reason, FinishCode
ORDER BY Numbers
FOR XML PATH('FinishCode'),
ROOT('UK_Products_Pipeline'),
TYPE
) -- Add This
FOR XML PATH('Dial_Stats') -- Add This
)
exec asp_Write_String_To_File #xml, #FilePath, #FileName
END
This then calls the stored procedure and the file is written to your
You could try write a quick c# console app to do this for you then just plug it into task scheduler?
The console app will run the query and get the result and then write it to a configured file location.

parsing multiple xml tags using openxml in sql server

<test>
<DBO.JOB>
<JOB_NO>234234</JOB_NO>
<CREW_NO>64850</CREW_NO>
<BEGINDATE></BEGINDATE>
<ENDDATE></ENDDATE>
</DBO.JOB>
<DBO.JOB>
<JOB_NO>234</JOB_NO>
<CREW_NO>234</CREW_NO>
<BEGINDATE></BEGINDATE>
<ENDDATE></ENDDATE>
</DBO.JOB>
<DBO.JOB>
<JOB_NO>324</JOB_NO>
234234
`
I want to know how to parse these tags using only OPEN XML and update them to a table DBO.JOB
Give this a try:
DECLARE #xml NVARCHAR(1000) =
'<test>
<DBO.JOB>
<JOB_NO>234234</JOB_NO>
<CREW_NO>64850</CREW_NO>
<BEGINDATE></BEGINDATE>
<ENDDATE></ENDDATE>
</DBO.JOB>
<DBO.JOB>
<JOB_NO>234</JOB_NO>
<CREW_NO>234</CREW_NO>
<BEGINDATE></BEGINDATE>
<ENDDATE></ENDDATE>
</DBO.JOB>
</test>'
DECLARE #hdoc int
EXEC sp_xml_preparedocument #hdoc OUTPUT, #xml
INSERT INTO DBO.JOB(JOB_NO, CREW_NO, BEGINDATE, ENDDATE)
SELECT *
FROM OPENXML(#hdoc, '/test/DBO.JOB', 2)
WITH (
JOB_NO INT,
CREW_NO INT,
BEGINDATE DATETIME,
ENDDATE DATETIME
)
EXEC sp_xml_removedocument #hdoc

The return types for the following stored procedures could not be detected

While drag-drop a stored procedure in dbml file I get this error:
Unknown Return Type
The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.
How can I resolve this error?
This problem occurs whenever the designer cannot figure out the return type of the SP.
Same problem and solutions described here
How to get multiple result set of procedure using LINQ to SQL
Basically this is the solution from the link:
Avoid using #temp Table in your stored procedure, instead of you can use Table type variable like below (#TempTable)
Ex:
DECLARE #TempTable TABLE
(
AttributeID INT,
Value NVARCHAR(200)
)
INSERT INTO #TempTable Select * from Attribute
OR
--Execute SP and insert results into #TempTable
INSERT INTO #TempTable Exec GetAttribute #Id
You can do all operation which you was doing with #Temp table like
Join, Insert, Select etc.
Add these lines right after parameters declaration
AS
IF 1=0 BEGIN
SET FMTONLY OFF
END
After this, write BEGIN and start your procedure work .
I was using a temp table in my SQL and was getting this error. I converted the temp table to table variables and that resolved my issue.
This can be also the problem of access rights. If the stored procedure doesn't have an access to the table you get the same error. I had a query selecting data from another database I didn't have rights for (in fact the account running the Visual Studio connection didn't have the rights) and I received the same error. After adding proper rights everything went fine.
Trying to execute the stored procedure inside VS2010 (by right clicking in Server Explorer and selecting "Execute") helped me to solve the problem.
I've just added about 300 stored procs to my DBML and experienced many of the problems noted here and elsewhere.
Here is a summary of the causes & solutions for the error "The return types for the following stored procedures could not be detected", based on what I have personally experienced. Note that the problems described below can occur in the SP that you are having the error with, or any other SP that is being called from that SP directly or indirectly.
Concatenating integers with string using a '+' symbol. Use CAST() on the integers, or in SQL2012 or higher use the CONCAT() statement.
Referencing tables in other databases. Apparently a permissions issue. I wasn't able to resolve this one.
Any direct or indirect call to XP_CMDSHELL. I wasn't able to resolve this one.
Any syntax error in direct or indirect calls to other stored procs. Fix the call to the SP.
Temp Tables. Replace the Temp Table with a Table Variable.
SET QUOTED_IDENTIFIER OFF is in use, but the table being edited has a Indexed View on it. *Change the set statement to SET QUOTED_IDENTIFIER ON.*
Reason: Your Stored Procedure will be returning a complex type. that is, multiple results or uses a temp table.
Resolution
It entirely depends on what your Stored Procedure is doing. Useful links
http://odetocode.com/code/365.aspx
http://riteshkk2000.blogspot.com/2010/08/error-unknown-return-type-return-types.html
Just in case anyone else comes across this, I have just experienced it myself.
In my case, I was referencing a table in an insert statement that no longer existed in my schema. A closer inspection of my code revealed I was inserting into a table called "Account" which was now called "tblAccount". Visual Studio threw no errors on saving the sp, but I experienced the same error when trying to add the sp to the dbml file.
Hopefully this will help someone else out.
I also had this problem - had to comment out code that was constructing a polygon:
declare
#MapBounds geography
;
select
#MapBounds = geography::STGeomFromText('POLYGON((' +
cast(#NorthEastLng as varchar) + ' ' + cast(#NorthEastLat as varchar) + ', ' +
cast(#SouthWestLng as varchar) + ' ' + cast(#NorthEastLat as varchar) + ', ' +
cast(#SouthWestLng as varchar) + ' ' + cast(#SouthWestLat as varchar) + ', ' +
cast(#NorthEastLng as varchar) + ' ' + cast(#SouthWestLat as varchar) + ', ' +
cast(#NorthEastLng as varchar) + ' ' + cast(#NorthEastLat as varchar) +
'))', 4326)
;
Once it was added to the dmbl, I un-commented out the code and it worked like a champ!
I also had the problem (VS 2012, SQL Server 2008R2). In my case it was a combination of the + operator and various CAST statements in the code. I haven't found a way to replace them with something VisualStudio likes, but I have come up with a workaround:
Workaround "Dummy SELECT":
Create a dummy SELECT statement with all the fields you need to return. For example:
select 'bla bla' as field1, 123123 as field2, 'asñfs' as field3
Comment out your SP code and just leave the dummy SELECT in your SP.
Add your SP in the O/R designer and save (it should do know without an error message)
Restore your original SP (leave the dummy SELECT as a comment for future use)
You might as well consider using CONCAT() method instead of '+' to concat a string. Since I wasn't using temp table and yet still encounter this problem. I found out that concating strings using '+' triggering this.
In my case, I was using this:
SET #errorMessage = CONCAT('Update (ID=', #pnID, ') failed. Name already exists.');
Instead of:
SET #errorMessage = 'Update (ID=' + #pnID + ') failed. Name already exists.';
Just ran into this issue while trying to add a stored procedure into a DBML (LINQ) file.
Doing some research I found that this usually happens when the stored procedure returns multiple results or uses a #temp table for it's final select.
The solution that worked for me was to create a new stored procedure that wrapped the results of the original stored procedure result, into a table variable with the same columns as the temp table.
My wrapper stored proc looked something like this:
DECLARE #NewPrograms TABLE (
Campaign_Number int,
Campaign_Display nvarchar(255)
)
INSERT INTO #NewPrograms
EXEC [dbo].[Original_Stored_Proc_With_Temp_Table_Result] #Program_ID
Select *
From #NewPrograms
Open up your DBML file, drag-and-drop in your new wrapper stored proc.
Make sure the stored procedure runs without erroring. Just had this problem and I assumed the person who made the stored procedure had tested it and did not try it myself.
The solution I found ... I put a SELECT on top (IF) with conditions that are not correct and create a variable table with the result he wanted to exit and then "ELSE" put things right. The first part is only if you understand the process output I want. Look at my example
ALTER PROCEDURE [dbo].[SS_getSearchedProductsDetailsNew]
(
#mk int,
#md int,
#yr int = 0,
#caroption int = 0,
#condition int = 0,
#producttype int = 0 ,
#option int = 0,
#coloroption int = 0
)
AS
declare #sql nvarchar(max)
Begin
if #mk = 0 and #md = 0 and #yr = 0
begin
Declare #TempTable2 TABLE(
ProductID numeric(10),
TypeName nvarchar(50),
MakeID numeric(10),
ModelID numeric(10),
ConditionID numeric(10),
CarOptionsID numeric(10),
OptionsID numeric(10),
ColorOptionsID numeric(10),
Make nvarchar(50),
Model nvarchar(50),
YearID numeric(5),
Color nvarchar(50),
ProductType nvarchar(50),
CarOptionName nvarchar(50),
OptionName nvarchar(50),
ColorOptionName nvarchar(50),
ConditionName nvarchar(50),
Notes nvarchar(500),
Price money,
cog money)
select * from #TempTable2
end
else
begin
select #sql = '
declare #theNotes nvarchar(500)
declare #theMake numeric(10), #theModel numeric(10), #theYear numeric(10)
declare #makeName nvarchar(50), #modelName nvarchar(50), #ID numeric(5)
declare #theProductType nvarchar(50), #theTypeName nvarchar(50)
declare #theColor nvarchar(50),#theProductID numeric(10)
declare #theCondition numeric(10),#theCarOption numeric(10) , #theOption numeric(10), #theColorOption numeric(10)
declare #theConditionName nvarchar(50),#theCarOptionName nvarchar(50), #theOptionName nvarchar(50),#theColorOptionName nvarchar(50)
declare #thePrice money, #theCog money
declare #HoldingTable table(
ID numeric identity,
ProductID numeric(10),
MakeID numeric(10),
ModelID numeric(10),
ConditionID numeric(10),
CarOptionsID numeric(10),
OptionsID numeric(10),
ColorOptionsID numeric(10),
Make nvarchar(50),
Model nvarchar(50),
YearID numeric(5),
Color nvarchar(50),
ProductType nvarchar(50),
Notes nvarchar(500),
Price money,
cog money);
INSERT INTO #HoldingTable (ProductID,MakeID, ModelID , ConditionID, CarOptionsID,OptionsID,ColorOptionsID, Make ,Model,YearID,Color, ProductType, Notes, Price, cog)
SELECT
ProductNumber as ProductID,
tblProductsForSale.MakeID as MakeID,
tblProductsForSale.ModelID as ModelID ,
ConditionID,
CarOptionsID,
OptionsID,
ColorOptionsID,
tblVehicleMake.Make as Make ,
tblVehicleModel.Model as Model,
YearID,
Color,
ProductType, Notes,
tblProductsForSale.ResalePrice as Price,
tblProductsForSale.SellPrice as cog
from tblProductsForSale, tblVehicleMake, tblVehicleModel where
tblProductsForSale.MakeID = tblVehicleMake.MakeID and
tblProductsForSale.ModelID = tblVehicleModel.ModelID
and tblProductsForSale.ProductStatus=''available'' and tblProductsForSale.Custom=0'
if(#mk > 0)
begin
select #sql = #sql + ' and tblProductsForSale.MakeID = ' + convert(varchar, #mk)
end
if #md > 0
Begin
select #sql = #sql + ' and tblProductsForSale.ModelID = ' + convert(varchar, #md)
End
if #yr > 0
begin
select #sql = #sql + ' and tblProductsForSale.YearID = ' + convert(varchar, #yr)
end
if #caroption > 0
begin
select #sql = #sql + ' and tblProductsForSale.CarOptionsID = ' + convert(varchar, #caroption)
end
if #producttype > 0
begin
select #sql = #sql + ' and tblProductsForSale.ProductType = ''' + convert(varchar,#producttype) + ''''
end
if #option > 0
begin
select #sql = #sql + ' and tblProductsForSale.OptionsID = ' + convert(varchar, #option)
end
if #coloroption > 0
begin
select #sql = #sql + ' and tblProductsForSale.ColorOptionsID = ' + convert(varchar, #coloroption)
end
--select #sqlInsert = 'INSERT INTO #HoldingTable (ProductID,MakeID, ModelID , ConditionID, CarOptionsID,OptionsID,ColorOptionsID, Make ,Model,YearID,Color, ProductType, Price, cog) '
--select #sqlExec = #sqlInsert + #sql
--select * from #HoldingTable
select #sql = #sql + 'Declare #TempTable2 TABLE(
ProductID numeric(10),
TypeName nvarchar(50),
MakeID numeric(10),
ModelID numeric(10),
ConditionID numeric(10),
CarOptionsID numeric(10),
OptionsID numeric(10),
ColorOptionsID numeric(10),
Make nvarchar(50),
Model nvarchar(50),
YearID numeric(5),
Color nvarchar(50),
ProductType nvarchar(50),
CarOptionName nvarchar(50),
OptionName nvarchar(50),
ColorOptionName nvarchar(50),
ConditionName nvarchar(50),
Notes nvarchar(500),
Price money,
cog money)
WHILE Exists(Select * from #HoldingTable )
begin
Select #ID = ID FROM #HoldingTable
Select #theProductId = ProductID from #HoldingTable
Select #theMake = MakeID from #HoldingTable
Select #theModel = ModelID from #HoldingTable
Select #theCondition = ConditionID from #HoldingTable
Select #theCarOption = CarOptionsID from #HoldingTable
Select #theOption = OptionsID from #HoldingTable
Select #theColorOption = ColorOptionsID from #HoldingTable
Select #theYear = YearID from #HoldingTable
Select #theColor = Color from #HoldingTable
Select #theProductType = ProductType from #HoldingTable
Select #theTypeName = TypeName from tblProductType WHere ProductTypeID = cast (#theProductType as numeric(10))
Select #thePrice = Price from #HoldingTable
Select #theCog = cog from #HoldingTable
Select #theConditionName = ConditionName from tblConditions Where ConditionID = #theCondition
Select #makeName = Make from tblVehicleMake Where MakeID = #theMake
Select #modelName = Model from tblVehicleModel Where ModelID = #theModel
Select #theCarOptionName = CarOptionsName from tblCarOptions Where CarOptionsID = #theCarOption
Select #theOptionName = OptionsName from tblOptions Where OptionsID = #theOption
Select #theColorOptionName = ColorOptionsName from tblColorOptions Where ColorOptionsID = #theColorOption
Select #theNotes = Notes from #HoldingTable
Select #theProductType = ProductType from #HoldingTable
INSERT INTO #TempTable2 (ProductID,TypeName,MakeID,ModelID,ConditionID ,CarOptionsID,OptionsID ,ColorOptionsID ,Make , Model , YearID ,Color, ProductType, CarOptionName ,OptionName,ColorOptionName ,ConditionName, Notes, Price, cog)
VALUES (#theProductId,#theTypeName, #theMake, #theModel, #theCondition, #theCarOption,#theOption,#theColorOption, #makeName,#modelName, #theYear, #theColor,#theProductType, #theCarOptionName, #theOptionName, #theColorOptionName, #theConditionName, #theNotes, #thePrice , #theCog )
DELETE FROM #HoldingTable Where ID = #ID
end
Select * from #TempTable2 order by ProductID '
end
exec ( #sql )
End
I've struggled a lot on this and came to conclusion, that if your stored procedure is dynamic and is combined with strings you sometimes miss something.. so while importing Visual Studio DBML import/update can not execute/test the procedure, so return type stays undefined, once you correct the procedure (query strings that you are building up to execute) you can add the procedure without any problems.
I had this error too and finally I found out that I have changed a table field name and in procedure it did not change it yet, and so it showed an error when adding to dbml.
Now you can check this on your procedure and your table that fields are the same.
I hope this experience is useful.
A simple way to solve this issue is (December 2019)
1 Just making double # precede #tmp => ##tmp
2 Comment out DROP TABLE #tmp => --DROP TABLE #tmp
Execute stored procedure and make sure that data showed up
Drag stored procedure again and that's it, It will generate return type
Last, Turn your store back to first situation and then save.
Hope I can help.
I got the same error when I dragged and dropped the stored procedure, so I just followed what the error said:
Unknown Return Type
The return types for the following stored procedures could not be detected. Set the return type for each stored procedure in the Properties window.
I selected the stored procedure and then selected properties tab, there there is a option called ReturnType which was empty and then hit the dropdown button on it and selected the table the SP was created and the issue is resolved.
If this doesn't help you can try any of the above answers.
The issue for me was that I had OPTION (RECOMPILE) set to get round a parameter sniffing issue. I temporary removed this while adding the SP and all worked fine.
You must place the
SET NOCOUNT ON;
SET FMTONLY OFF
at the top of the procedure . Like for example:
ALTER PROCEDURE [dbo].[usp_Name]
#your_params
AS
BEGIN
SET NOCOUNT ON;
SET FMTONLY OFF
-- your other codes
End