Click here to Skip to main content
15,908,166 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi everybody.
I'm trying to populate an sql 2012 table using a datatable passed via c# code, using a stored procedure and a user defined table as type.

I assume that the datatable, as well as the c# code are ok, because if my end table is empty everything works like a charm.

But if I already have some records in the end table, the stored procedure does update them but it doesn't insert the new ones.

This is my stored procedure:

USE [FTBL]
GO
/****** Object:  StoredProcedure [dbo].[usp_insCountries]    Script Date: 31/08/2014 11:49:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[usp_insCountries] @dt AS dbo.udt_InsCountries READONLY
AS
BEGIN
	UPDATE dbo.tbl_countries_feed
	SET country_Id = dt.country_Id,
	country_Name = dt.country_Name,
	country_Fifa_Code = dt.country_Code
	FROM dbo.tbl_countries_feed AS countries INNER JOIN @dt AS dt
	ON countries.country_ID = dt.country_Id;

	/*WITH countries AS
	(SELECT country_Id, country_Name, country_Code FROM @dt AS dt 
	WHERE NOT EXISTS (SELECT country_ID FROM dbo.tbl_countries_feed))
	*/
  INSERT dbo.tbl_countries_feed(country_Id, country_Name, country_Fifa_Code)
	SELECT country_Id, country_Name, country_Code FROM @dt
	WHERE NOT EXISTS (SELECT country_Id, country_Name, country_Code FROM dbo.tbl_countries_feed);
END


I think there's something wrong with the not exists clause..
As you can see, I also tried using a CTE to filter the records in a first step, but nothing changed.

Any suggestion?

Thx in advance.
Posted

1 solution

Gotcha!

USE [FTBL]
GO
/****** Object:  StoredProcedure [dbo].[usp_insCountries]    Script Date: 31/08/2014 11:49:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[usp_insCountries] @dt AS dbo.udt_InsCountries READONLY
AS
BEGIN
	UPDATE dbo.tbl_countries_feed
	SET country_Id = dt.country_Id,
	country_Name = dt.country_Name,
	country_Fifa_Code = dt.country_Code
	FROM dbo.tbl_countries_feed AS countries INNER JOIN @dt AS dt
	ON countries.country_ID = dt.country_Id;

	/*WITH countries AS
	(SELECT country_Id, country_Name, country_Code FROM @dt AS dt 
	WHERE NOT EXISTS (SELECT country_ID FROM dbo.tbl_countries_feed))
	*/
  INSERT dbo.tbl_countries_feed(country_Id, country_Name, country_Fifa_Code)
	SELECT country_Id, country_Name, country_Code FROM @dt as dt
	WHERE country_Id NOT IN(SELECT country_Id FROM dbo.tbl_countries_feed)
END


I just need to make my T-SQL knowledge deeper..

Have a nice Sunday!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900