ADO.NET Retrieve UDT Columns from SQL Server 2012? - sql-server

I can use code like this to extract the columns from a SQL Server 2012 table:
var sqlConnection = new SqlConnection(conns);
var dt = sqlConnection.GetSchema
(SqlClientMetaDataCollectionNames.Columns, new string[] { null , null , "mytable" , null });
However, I am unable to determine the right kind of schema query to get the columns from my user-defined Table type. How is that done?
All ideas appreciated (Using .NET 4.5.1).

Not sure if this is still a relevant question, but I just received an answer to something nearly identical. Check out the answer for this question:
Retrieve UDT table structure in VB.NET
The answer shows how to get a "sanitized" type name from sys.types, then it creates simple sql query in the form:
declare #t MyUDTType; select * from #t;
Then returns the empty DataTable to the calling application.

Related

How can we use data in result tables in coding with SQL in Visual Studio?

I am coding with Visual Studio 2013 and SQL Server 2012. Sometimes we have to use the data in result tables for our code. As an example, if we compare two tables using SELECT, EXCEPT method, we can see the differentiated entries between those two tables in result window as a another table.
So, I asked, if I need to add that result data into a table in my database, how can I do it? Is it possible or not and are there any method to do it?
Sample
If you are asking for SQL, you can do something like this for table that already created:
INSERT INTO NEW_TABLE (col1,col2,...)
SELECT col1,col2,...
FROM YOUR_TABLE
EXCEPT SELECT ...
Or if you want to create a new table using that query without specifying each columns (copy the column specs from the source table), you can do something like this:
SELECT ...
INTO NEW_TABLE
FROM YOUR_TABLE
EXCEPT
SELECT ...
FROM ANOTHER_TABLE
If your new table want to drop after you have processed with your data, consider #temptable or #tablevariable.
But if you just want to do some processing in the resulting table but do not want to store it in database, I recommend using DataTable in .NET by doing something like this:
using System;
using System.Data;
//...
DataTable dttbl = new DataTable();
dttbl.TableName = "YOUR_TABLE";
dttbl.Load(new SqlCommand("SELECT ...",sqlConnection).ExecuteReader());
//process your datatable using indexing like this
dttbl.Rows[(row_number (int))][(column_name (string), column_position (int))] = "Processed";
dttbl.Rows[0]["col1"] = "Processed"; //This line will change the value in cell of the first record in column named "col1" to "Processed".
EDIT*: More about dataTable
To print out a whole DataTable
//Print out the columns name
for(int i=0;i<dttbl.Columns.Count;i++)
Console.Write(dttbl.Columns[i].ColumnName + " ");
Console.Write("\n");
//Print out the data
for(int i=0;i<dttbl.Rows.Count;i++)
{
for(int k=0;k<dttbl.Columns.Count;k++)
{
Console.Write(dttbl.Rows[i][k] + " ");
}
Console.Write("\n");
}
Note: SQL is database query language while C#,VB or other .NET language is programming language. In short, database query language is a way for programming language to communicate with database.

How to insert data table by stored procedure in SQL SERVER

tried to insert many records of a data table to SQL table by stored procedure.I need insert data table's records all together.
I'm using C# programming language and i want to send many records to SQL server by ADO.net stored procedure all together. i want to know about data table types and use it if that helps me.
To pass many rows efficiently to a stored procedure, use a table-valued parameter. The C# app can specify parameter type structured and a value of a data table. For maximum performance, make sure the DataTable column types match the server-side table type column types (including max length for string columns).
Below is an example excerpt from the documentation link above:
// Assumes connection is an open SqlConnection object.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(DataRowState.Added);
// Configure the SqlCommand and SqlParameter.
SqlCommand insertCommand = new SqlCommand("usp_InsertCategories", connection);
insertCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
// Execute the command.
insertCommand.ExecuteNonQuery();
}
Here are T-SQL snippets to create the table type and proc.
CREATE TYPE dbo.CategoryTableType AS TABLE
( CategoryID int, CategoryName nvarchar(50) );
GO
CREATE PROC dbo.usp_InsertCategories
AS
#tvpNewCategories dbo.CategoryTableType READONLY
INSERT INTO dbo.Categories (CategoryID, CategoryName)
SELECT nc.CategoryID, nc.CategoryName FROM #tvpNewCategories AS nc;
GO
Even for trivial inserts, TVP performance can provide performance similar to SqlBulkCopy (many thousands per second) with the advantage of a stored procedure interface.

Why can't SQL Server database name begin with a number if I run a query?

Recently I found an anomaly with SQL Server database creation. If I create with the sql query
create database 6033SomeDatabase;
It throws an error.
But with the Management Studio UI, I can manually create a database with a name of 6033SomeDatabase.
Is this expected behaviour or is it a bug? Please throw some light on this issue.
Try like this,
IF DB_ID('6033SomeDatabase') IS NULL
CREATE DATABASE [6033SomeDatabase]
I'll try to give you detailed answer.
SQL syntax imposes some restrictions to names of database, tables, and fields. F.e.:
SELECT * FROM SELECT, FROM WHERE SELECT.Id = FROM.SelectId
SQL parser wouldn't parse this query. You should rewrite it:
SELECT * FROM [SELECT], [FROM] WHERE [SELECT].Id = [FROM].SelectId
Another example:
SELECT * FROM T1 WHERE Code = 123e10
Is 123e10 the name of column in T1, or is it a numeric constant for 123×1010? Parser doesn't know.
Therefore, there are rules for naming. If you need some strange database or table name, you can use brackets to enclose it.

SQL Server to Teradata migration

We are migrating from SQL Server to Teradata database. All the views and tables are migrated. But the issue is that we aren't able to take the comments from each table.
In SQL Server we have a function called extended property which if used will get the comments from the respective tables/views. Badhri helped with providing a query for fetching the comment in Teradata in the same way but it doesn’t work in the expected way.
I tried inserting sample comments in columns and the below query is not fetching exact results. Can you please help?
Sample Query:
COMMENT ON COLUMN UtilityApp_DB.SQL_Views_Columns.ColumnNAME 'A Columnname for SQL Server!';
select 'COMMENT ON COLUMN '||trim(b.databasename)||'.'||trim(b.tablename) ||'.'||trim(b.columnname)||' IS '||''''||trim(b.commentstring)||''';'
FROM DBC.Columns b
WHERE b.CommentString IS NOT NULL
AND DatabaseName='UtilityApp_DB'
AND TableName in ('UtilityApp_DB.SQL_Views_Columns');
I created a table and tried inserting the values for the comment string in the table by copying the DBC Columns structure but still I can't get the comment string.
insert into UtilityApp_DB.commentstable (commentstring) values ('UtilityApp_DB.SQL_Views_Columns');
TableName in DBC.Columns does not include the database name and IS in your string concatenation should be AS.
SELECT 'COMMENT ON COLUMN '||trim(b.databasename)||'.'||trim(b.tablename) ||'.'||trim(b.columnname)||' AS '||''''||trim(b.commentstring)||''';'
FROM DBC.Columns
WHERE DatabaseName = 'UtilityApp_DB'
AND TableName IN ('SQL_Views_Columns');

Storing native language strings in SQL columns with user defined datatypes

My Table name is property_pair_master. And one of the column in it is
prop_value (its datatype is varchar(max));
I created my userdefined datatype using the below query
EXEC sp_addtype 'tinyUTF8','varbinary(8000)','NULL'
Now I changed the datatype to my tinyUTF8 (my defined datatype).
Problem is when I am trying to update the value in it using the below query
update property_pair_master set prop_value =
CONVERT('મારું માહિતી પરીક્ષણ' AS tinyUTF8) where id=1
getting the error message as
Incorrect syntax near 'મારું માહિતી પરીક્ષણ'.
How can I update the String into Database?
Is there any alternative to do this. Any suggestions ?
Note : I am using SQL SERVER 2008.
Thanks in advance.
HHHahh...
I found the solution and got rid off cast and convert
Updated the datatype to nvarchar(MAX) .And I updated my query as
update property_pair_master set prop_value = N'વ્યાવહારિક' where id=1

Resources