sql tables to xml - c#

I have got few tables in sql database, one of that contains names of others, but not all. I need to load names of tables (from that special one) as a list (xdocument), and using foreach and a simple query convert all of that to one xml file. database and app is on same azure account.
i have few table like that
CREATE TABLE [dbo].[table_name]
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
and one with only varchar that contains
table_name1
table_name2
table_name4
i use that simple query
SELECT
P_ID "Table_name2/#id",
nazwa "Table_name2"
FROM Table_name2
FOR XML PATH('');
and get result, but only for one table
something
but i want a result for few tables in one xml using "file_converting_tables_to_xml.cs" in my app
<spinery>
<spiner title="Table_name1">
<wart id="1">black</wart>
</spiner>
<spiner title="Table_name3">
<wart id="1">white</wart>
</spiner>
or something similar
all that i found about it don't work for me,
so please help

If this was SQL Server you might try this:
--Creating two tables
CREATE TABLE [dbo].Table_name1
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
CREATE TABLE [dbo].Table_name2
(
[P_ID] INT NOT NULL,
[name] NVARCHAR (255) NOT NULL,
PRIMARY KEY CLUSTERED ([P_ID] ASC)
);
GO
--Fill them with your sample data
INSERT INTO dbo.Table_name1 VALUES(1,'black');
INSERT INTO dbo.Table_name2 VALUES(1,'white');
GO
--Use UNION ALL to combine the results and FOR XML PATH to create the proper namings
SELECT 'Table_name1' AS [#title]
,P_ID [wart/#id]
,name [wart]
FROM Table_name1
UNION ALL
SELECT 'Table_name2' AS [#title]
,P_ID [wart/#id]
,name [wart]
FROM Table_name2
FOR XML PATH('spiner'),ROOT('spinery');
--Clean-Up (Carefull if real data!)
GO
--DROP TABLE dbo.Table_name1;
--DROP TABLE dbo.Table_name2;

Related

Insert to SQL Server from table type fails if more than 1 row

The following procedure gets data from C# as a datatable. I am sure that the table is sent with multiple rows. If it does have multiple rows, then no data is inserted, but if the data table contains only one row, it inserts it without any problems.
ALTER PROCEDURE [dbo].[MergeContactInfo]
#ContactInfo dbo.[PersonContactTableType] READONLY
AS
BEGIN
MERGE INTO PersonContact AS pc
USING #ContactInfo AS ci ON pc.Person = ci.Person
WHEN MATCHED THEN
UPDATE SET pc.Value = ci.Value, pc.Type = ci.Type
WHEN NOT MATCHED THEN
INSERT VALUES(ci.Person, ci.Type, ci.Value);
END
Any solution why multiple rows not inserted and only one row is inserted, there's no unique constraints.
#Contact Info is the following
CREATE TYPE [dbo].[PersonContactTableType] AS TABLE(
[Person] [int] NOT NULL,
[Type] [tinyint] NOT NULL,
[Value] [varchar](100) NOT NULL,
PRIMARY KEY CLUSTERED ([Person] ASC) WITH (IGNORE_DUP_KEY = OFF)
)
GO
Check your C# datatable content. Each number in "Person" field must be unique. Procedure perfectly works as designed.
Your code works perfect on SQL side,
I tested playing with the content of the table variable and I see that it is merged with table data as expected
declare #CI as [PersonContactTableType];
insert into #CI values (11,1,'ERALPER'),(12,2,'The Phantom'),(13,2,'Lord Vader'),(14,1,'Kodyaz')
exec [MergeContactInfo] #CI;
go
select * from PersonContact

Minimizing select time in Varbinary(max) column

I am facing a issue with latency when I select images which are saved in a varbinary(max) column in SQL Server, it takes around 3-5 mins to select at least 5 images. This table (galleryDetail) contains images with different sizes like 2mb, 40kb, 1mb likewise. As suggested in this link SQL server slow select query from type varbinary(max) (last comment),if somebody could give me a road map/suggestion, to achieve this task, it would be a big Help.
My table structure is as follows,
CREATE TABLE [dbo].[GalleryDetail]
(
[Id] [INT] IDENTITY(1,1) NOT NULL,
[Image] [VARBINARY](MAX) NULL,
[Title] [VARCHAR](250) NULL,
[Active] [BIT] NULL,
[CreatedDate] [DATETIME] NULL,
CONSTRAINT [PK_ImageGallery]
PRIMARY KEY CLUSTERED ([Id] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[GalleryDetail]
ADD CONSTRAINT [DF_GalleryDetail_Active] DEFAULT ((1)) FOR [Active]
GO
If you select by Title column then add index to make select faster:
create index idx_Title on dbo.GalleryDetail(Title)
This only helps if Title is in the where clause of your query, e.g.
select * from GalleryDetail where Title = 'My picture'
or
select * from GalleryDetail where Title like 'picture%'

ContentType - Dynamic Data Structure Storage C# + SQL Server

I have an assignment - I need to store dynamic content in database in form of content types.
ContentTypes are basically a key-value collection. I need to store this data in database and make sure the content types are queryable and can be indexed. I can't create a table for each content type because they can be changed at runtime and that would mean dropping of table and losing data.
Does anyone know any good approach for this? I need to mention that DB will in the end contain ~1 million content types. In the end this data would be accessed by .NET application.
if values should be queryable then you can work as following sample
CREATE TABLE [dbo].[ContentTypeDetail]
(
[ContentTypeDetailId] uniqueidentifier NOT NULL,
[ContentTypeId] uniqueidentifier NOT NULL,
[ColumnType] smallint NOT NULL,
[ColumnValueString] nvarchar(1000) NULL,
[ColumnValueInt] int NULL
)
GO
ALTER TABLE [dbo].[ContentTypeDetail] ADD CONSTRAINT [ContentTypeDetail_PK] PRIMARY KEY CLUSTERED
(
[ContentTypeDetailId]
)
GO
CREATE TABLE [dbo].[ContentType]
(
[ContentTypeId] uniqueidentifier NOT NULL,
[Name] nvarchar(100) NOT NULL
)
GO
ALTER TABLE [dbo].[ContentType] ADD CONSTRAINT [ContentType_PK] PRIMARY KEY CLUSTERED
(
[ContentTypeId]
)
GO
ALTER TABLE [dbo].[ContentTypeDetail] WITH CHECK ADD CONSTRAINT [ContentType_ContentTypeDetail_FK1] FOREIGN KEY
(
[ContentTypeId]
)
REFERENCES [dbo].[ContentType]
(
[ContentTypeId]
)
GO
of course you have to add appropriate indexes

Failed to insert data through LINQ to SQL server

I'm trying to insert data into the database using LINQ. In me SQL server side I wrote a sequence to generate a custom id with a prefix. Here what I did in my code,
ALLibraryDataClassesDataContext dbContext = new ALLibraryDataClassesDataContext();
dbContext.Books.InsertOnSubmit(book);
dbContext.SubmitChanges();
dbContext.Dispose();
In my book object I'm not setting the BookID because it's generating from the sequence. When I'm executing
INSERT INTO library_db.dbo.Book([BookName]) VALUES ('SH')
This inserts data with the auto generated id. But when I'm running the code, It gives an SQLException,
Cannot insert the value NULL into column 'BookId', table 'library_db.dbo.Book'; column does not allow nulls. INSERT fails.
EDITED
My sequence and table creation,
CREATE TABLE [dbo].[Book] (
[BookId] VARCHAR (50) NOT NULL,
[BookName] VARCHAR (50) NULL,
[AuthorName] VARCHAR (50) NULL,
[PublisherName] VARCHAR (50) NULL,
[PublishedDate] DATE NULL,
[price] MONEY NULL,
[PurchasedDate] DATE NULL,
[PurchasedBillNo] VARCHAR (50) NULL,
[CategoryId] VARCHAR (50) NULL,
[NoOfCopies] VARCHAR (50) NULL,
[FinePerDay] MONEY NULL,
[BookImage] VARCHAR (2000) NULL,
PRIMARY KEY CLUSTERED ([BookId] ASC),
CONSTRAINT [FK_Book_Category] FOREIGN KEY ([CategoryId]) REFERENCES [dbo].
[Category] ([CategoryId])
);
GO
CREATE SEQUENCE dbo.BookId_Seq AS
INT START WITH 1
INCREMENT BY 1 ;
GO
ALTER TABLE dbo.Book
ADD CONSTRAINT Const_BookId_Seq
DEFAULT FORMAT((NEXT VALUE FOR dbo.BookId_Seq),'B0000#') FOR [BookId];
GO
What is the different between running a query manually and through LINQ? Is there a possible way to insert data into code(LINQ) with a custom id?
I'm not sure if you can do this with LINQ-to-SQL, but give it a try:
In the context designer, set "Auto Generated Value" = true for BookId. This tells LINQ-to-SQL to exclude the column from insert statements. Now the database will fall back to the default constraint, which doesn't happen when an insert statement supplies a value.
However, there may be one problem. When auto-generated value is defined for a primary key column, LINQ-to-SQL will try to read the generated value afterwards by a select statement looking like
SELECT CONVERT(Int,SCOPE_IDENTITY()) AS [value]
Obviously, drawing the value from a sequence will leave SCOPE_IDENTITY() undefined. At best this will prevent you from reading the generated key value from the book variable after SubmitChanges, but in the worst case it will cause an error that you can't work around.

Cannot insert the value NULL into column 'rowguid', column does not allow nulls. INSERT fails

How can I avoid this problem:
Cannot insert the value NULL into column 'rowguid', column does not allow nulls. INSERT fails.
Sample query is:
insert into tablename (col1, col2, col3)
values('v1', 'v2', 'v3')
If you are not going to insert the value explicitly in the INSERT statement, and the columns is NOT NULL, you need to specify a default value in the TABLE.
The DEFAULT constraint is used to insert a default value into a
column. The default value will be added to all new records, if no
other value is specified.
It sounds like your table has been created with a ROWGUIDCOL but without the appropriate default value. Here is an example from ASP.NET forum for a proper table definition using the feature. It should give you some help.
CREATE TABLE Globally_Unique_Data
(guid uniqueidentifier CONSTRAINT Guid_Default DEFAULT NEWSEQUENTIALID() ROWGUIDCOL,
Employee_Name varchar(60)
CONSTRAINT Guid_PK PRIMARY KEY (Guid) );
The NEWSEQUENTIALID() default will generate a GUID for you. Without it you will have to generate your own and include it in the insert. You don't have to use it as the primary key as in the example, but you have to supply it or use the default.
There are two solutions to this problem.
One you can make column 'rowguid' to allow null and the other is to set some default value of your parameters.
In your code you can set values as
int v1 = 0;
string v2 ="";
Then pass these values to query.
You can set default parameter values in the stored procedure as
#v1 int = 0,
#v2 varchar(50) = ' '
Follow this example:
CREATE TABLE [dbo].[Files](
[id] [int] IDENTITY(1,1) NOT NULL,
[IdFile] [uniqueidentifier] unique ROWGUIDCOL NOT NULL,
[Title] [nvarchar](max) NULL,
[File] [varbinary](max) FILESTREAM NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[id] ASC
))

Categories

Resources