Given this EXACT ad-hoc query:
DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
VALUES ('Otter', 'Lebron', 'Aaron', 'Brock')
SELECT *
FROM Users
WHERE FirstName in (SELECT Name from #list)
How can this be done using C# ADO.NET with a SqlParameter?
I'm using a modification of your orginal SQL for sample purposes.
DECLARE #list AS TABLE (Name VARCHAR(20));
INSERT INTO #list(Name)
VALUES ('PROCEDURE'),
('FUNCTION');
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)
You can use a Table-Valued Parameter
Here's a modified example taken from Table-Valued Parameters in SQL Server 2008 (ADO.NET)
using (SqlConnection cnn = new SqlConnection("Your connection string"))
{
var tableParam = new DataTable("names");
tableParam.Columns.Add("Name", typeof(string));
tableParam.Rows.Add(new object[] { "PROCEDURE" });
tableParam.Rows.Add(new object[] { "FUNCTION')" });
var sql = #"DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
SELECT Name from #Names;
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)";
var sqlCmd = new SqlCommand(sql, cnn);
var tvpParam = sqlCmd.Parameters.AddWithValue("#Names", tableParam);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.Names";
cnn.Open();
using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
{
while (rdr.Read())
Console.WriteLine(rdr["SPECIFIC_NAME"]);
}
}
But you need to define the type dbo.Names before it can work
Here's the type creation SQL
CREATE TYPE dbo.Names AS TABLE
( Name VARCHAR(Max));
Another option is to use an XML Parameter
using (SqlConnection cnn = new SqlConnection("Your connection string"))
{
var sql = #"DECLARE #list AS TABLE (Name VARCHAR(20))
INSERT INTO #list(Name)
SELECT t.name.value('.', 'varchar(MAX)')
FROM #Names.nodes('/Names/Name') as T(Name);
SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from #list)";
var sqlCmd = new SqlCommand(sql, cnn);
var s = new MemoryStream(ASCIIEncoding.Default.GetBytes("<Names><Name>PROCEDURE</Name><Name>FUNCTION</Name></Names>"));
var xmlParam = new SqlXml(s);
sqlCmd.Parameters.AddWithValue("#Names", xmlParam);
cnn.Open();
using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
{
while (rdr.Read())
Console.WriteLine(rdr["SPECIFIC_NAME"]);
}
}
Related
Given that I have a Google sheet similar to this:
ID;username,email,date_created;
hdJNGDyd;user;me#example.com;12/03/2020 4:20:22
...
Is there a way to determine the formats of the Sheet columns and list them?
eg.
ID - string(8)
username - varchar(34)
email - varchar(255)
date_created - datetime
or map the sheet structure to a SQL query similar to:
CREATE table MyTable
`ID` varchar(8) NOT NULL
...
The length could be for example maximum length of the values in the particular column.
I would create a tab with a table listing the data dictionary
However, sheets has a TYPE() function you can use. If you also wanted to get the max length that would require some additional calculations.
So as you can see there is no date type and only a number type. Much different than what SQL offers.
In some of my projects I use google app script to get the schema from the MySQL database and then act accordingly
function getColTypes(conn, table) {
var stmt = conn.createStatement();
var query = "SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='" + DATABASE + "' AND TABLE_NAME='" + table + "'";
var rs = stmt.executeQuery(query);
var colTypes = [];
while (rs.next()) {
colTypes.push(rs.getString(1));
}
rs.close();
stmt.close();
return colTypes;
}
And this one for the names
function getColNames(conn, table) {
var stmt = conn.createStatement();
var query = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='" + DATABASE + "' AND TABLE_NAME='" + table + "'";
var rs = stmt.executeQuery(query);
var colNames = [];
while (rs.next()) {
colNames.push(rs.getString(1));
}
rs.close();
stmt.close();
return colNames;
}
I am trying to do an insert using linq to sql but am getting the following error
Additional information: Cannot insert the value NULL into column 'UserID', table 'Itiss_Request.dbo.Users'; column does not allow nulls. INSERT fails.
The UserID table is the pk aswel as the identity has been set to autoincrement.
The database has 4 fields.
DataClasses1DataContext dt = new DataClasses1DataContext();
User usr = new User();
usr.MudID = a[1];
usr.Email = Session["email"].ToString();
usr.Name = Session["userName"].ToString();
dt.Users.InsertOnSubmit(usr);
dt.SubmitChanges();
This is an from my context file
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_UserID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int UserID
{
get
{
return this._UserID;
}
set
{
if ((this._UserID != value))
{
this.OnUserIDChanging(value);
this.SendPropertyChanging();
this._UserID = value;
this.SendPropertyChanged("UserID");
this.OnUserIDChanged();
}
}
}
Please try this...
DataClasses1DataContext dt = new DataClasses1DataContext();
User usr = new User();
usr.MudID = a[1];
usr.Email = Session["email"].ToString();
usr.Name = Session["userName"].ToString();
dt.Users.AddObject(usr);
dt.SaveChanges();
im working in mvc and use sql command to insert data to my
database.
what i try to do is insert into 2 tables which one of them
have the foreign key from the other.
how can i build my sql query to make a condition on insert
into the table Image, insert the id in the foreignkey column
in the table Content.
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd;
System.Text.StringBuilder sql = new System.Text.StringBuilder();
sql.Append("insert into Image(FileName)");
sql.Append("values (#FileName)");
SqlCommand cmd2;
System.Text.StringBuilder sql2 = new System.Text.StringBuilder();
sql.Append("insert into Code(Html,JsCode,Id_Img)");
sql.Append("values (#Html, #JsCode, #Id_Img)");
cn.Open();
cmd = new SqlCommand(sql.ToString(), cn);
cmd.Parameters.Add("#FileName", SqlDbType.VarChar).Value = myfilename;
int FileId = (int)cmd.ExecuteScalar();
cmd2 = new SqlCommand(sql2.ToString(), cn);
cmd2.Parameters.Add("#Html", SqlDbType.VarChar).Value = mydiv;
cmd2.Parameters.Add("#JsCode", SqlDbType.VarChar).Value = DBNull.Value;
cmd2.Parameters.Add("#Id_Img", SqlDbType.Int).Value = FileId;
cmd2.ExecuteNonQuery();
cn.Close();
}
I think you can use ExecuteScalar() instead ExecuteNonQuery() to get the Scope_identity() value from the server like below and add that FileId to the second query.
using (SqlConnection cn = new SqlConnection("your_connection_string"))
{
string sql1 = "insert into Image(FileName) values (#FileName); " +
"SELECT CAST(scope_identity() AS int)";
string sql2 = "insert into Code(Html,JsCode,Id_Img) values (#Html, #JsCode, #Id_Img)";
int FileId = 0;
using (SqlCommand cmd = new SqlCommand(sql1,cn))
{
cmd.Parameters.AddWithValue("#fileName", myfilename);
cn.Open();
FileId= (int)cmd.ExecuteScalar();
}
}
I need a second pair of eyes. I'm getting that error in my C# code when I try calling the stored proc in question.
We're running SQL Server 2008 and here's my C# code and stored proc setup:
SqlConnection oConn = null;
string Name = "Frank";
bool IsEmp = true;
int RID = 31;
oConn = SQLConnectionHelper.GetConnection(SQLConnectionHelper.OurDB);
var sqlParams = new SqlParameter[3];
sqlParams[0] = new SqlParameter("#RID", RID);
sqlParams[1] = new SqlParameter("#Name", Name);
sqlParams[2] = new SqlParameter("#IsEmp", IsEmp);
SqlHelper.ExecuteNonQuery(oConn, CommandType.StoredProcedure, "dbo.OurStoredProc", sqlParams);
Start of the stored procedure:
ALTER PROCEDURE [dbo].[OurStoredProc]
(
#RID INT,
#Name nvarchar(20),
#IsEmp BIT
)
As
BEGIN TRANSACTION
What am I missing here?
I don't get it!
I'm doing a simple insert in an access db.
static void EcrireDansBD()
{
//Connection a la BD
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=me.mdb";
OleDbConnection conn = new OleDbConnection(connectionString);
//works
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV) VALUES (1,2,3)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,'ok')";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,ok)";
//Syntax error in INSERT INTO statement
string sql = "INSERT INTO HQ_POINTS (NORD,EST,ELEV,DESC) VALUES (1,2,3,\"ok\")";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Here is the table:
alt text http://img1.imagilive.com/0810/Capturee43.PNG
Help?
DESC is a reserved keyword which is used for ordering (ORDER BY column ASC/DESC).
you have to quote it: use [DESC] instead