I have this scenario :
I have a user table that has two column: Name and family.
what I want is that when user search a keyword ,for example 'name1 family1' ,all the result that have name: name1 and family: family1.
this is only one example and and my scenario is very complicated.(I want search name,lastname in one tables and phone number,address,so on related to current table).:(
is this search like google in an sql database possible? how? can I use fulltextsearch for this? how?
thank you.
Yes, it is possible. Create a view with schemabinding on your table with two columns: The ID (as PK) and a combined string of all fields you want to include in the full text search.
create view [dbo].[View_FamilyData]
with schemabinding as
select ID,
LastName+' '+FirstName+' '+Phone+' '+Address as SearchText
from dbo.YourTable
Then put a fulltext index on the the column SearchText.
Finally, play around with the various possiblities of CONTAINS,FREETEXT, CONTAINSTABLE and FREETEXTTABLE.
select T.*
from YourTable T
join View_FamilyData v
on v on T.ID = v.ID
where contains (SearchText,'Smith 12345')
private void tbautocomplete_TextChanged(object sender, EventArgs e)
{
AutoCompleteStringCollection namecollection = new AutoCompleteStringCollection();
SqlConnection con = new SqlConnection(#"Data Source=88888;Initial Catalog=contrynames;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT distinct(person_Firstname+''+person_Lastname) AS name FROM persondetails WHERE name Like '%'+#name+'%'";
con.Open();
SqlDataReader rea = cmd.ExecuteReader();
if (rea.HasRows == true)
{
while (rea.Read())
namecollection.Add(rea["name"].ToString());
}
rea.Close();
tbautocomplete.AutoCompleteMode = AutoCompleteMode.Suggest;
tbautocomplete.AutoCompleteSource = AutoCompleteSource.CustomSource;
tbautocomplete.AutoCompleteCustomSource = namecollection;
Related
What is the procedure to get the parameter and return types of a stored procedure? (Google is of no help :-( ).
Something along the lines of:
using (var conn = new Npgsql.NpgsqlConnection(connectionString: c))
{
conn.Open();
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "\"GetAllDx\"";
cmd.CommandType = CommandType.StoredProcedure;
cmd.GETPARAMETERS()????????
}
}
PostgreSQL 9.5
Npgsql 3.0.5
Here is one way:
SELECT pg_get_function_result(oid), pg_get_function_arguments(oid)
FROM pg_proc
WHERE proname = 'GetAllDx'
You may also find this useful (although this query returns more than you've asked for):
SELECT oid::regprocedure FROM pg_proc WHERE proname = 'GetAllDx'
I am using the following code to export data from excel to Sql server database. What is going on with this code is, its importing complete data into the database.
[HttpPost]
public ActionResult Importexcel()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string extension = System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = #"Data Source=xyz-101\SQLEXPRESS;Database=PracDB;Trusted_Connection=true;Persist Security Info=True";
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnectionString);
sqlBulk.DestinationTableName = "Excel_Table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
return RedirectToAction("Index");
}
How to check that any particular record already exist in the database or not. If not then Insert the record into the databse else it should not.
Thanks in Advance !
Since your target is SQL Server, you can use this to your advantage.
What I would do is read the data from the excel into a DataTable (instead of using a DataReader you can use a DataAdapter), Send that DataTable to a stored procedure in the SQL server, and handle the insert there. In order to sand a data table to a stored procedure you first need to create a Table-value user defined type in your sql server, like this:
CREATE TYPE MyType AS TABLE
(
Id int,
Name varchar(20), -- use whatever length best fitted to your data
Designation varchar(max) -- use whatever length best fitted to your data
)
Then you can write a simple stored procedure with an argument of this type:
CREATE PROCEDURE InsertDataFromExcel
(
#ExcelData dbo.MyType readonly -- Note: readonly is a required!
)
AS
INSERT INTO MyTable(Id, Name, Designation)
SELECT a.Id, a.Name, a.Designation
FROM #ExcelData a LEFT JOIN
MyTable b ON(a.Id = b.Id)
WHERE b.Id IS NULL -- this condition with the left join ensures you only select records that has different id values then the records already in your database
in order to send this parameter to the stored procedure from your c# code you will have to use a SqlCommand object and add the DataTable as a parameter, something like this:
using(SqlConnection Con = new SqlConnection(sqlConnectionString))
{
using(SqlCommand InsertCommand = new SqlCommand("InsertDataFromExcel", Con))
{
SqlParameter MyParam = new SqlParameter("#ExcelData", SqlDBType.Structured);
MyParam.Value = MyDataTable; // this is the data table from the
InsertCommand.Parameters.Add(MyParam);
Con.Open();
InsertCommand.ExecuteNoQuery();
Con.Close();
}
}
Note: Code was writen directly here, some errors might be found.
I know for sure this table exists yet the reader has no rows. I expect the name of the table to come back if it exists
using (var cmd = new SqlCommand("SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'" + tableName + "') AND type in (N'U')", SqlConnection))
{
var reader = cmd.ExecuteReader();
{
using (reader)
{
if (!reader.HasRows) return false;
while (reader.Read())
tableNameFound = reader.GetString(0);
}
}
}
I ran this query straight up in Management Studio and I do get back "Cars":
SELECT name FROM sys.objects
WHERE object_id = OBJECT_ID(N'Cars') AND type in (N'U')
so maybe I shouldn't be using reader here? I don't know.
Your query is fine.
Check:
If you run this on the correct database / schema. This query will fail when running it in master for example when your table is in another database / schema;
If the parameter you enter doesn't contain spaces, etc.
I have a table in C#, the data is coming from an Excel file. I need this data to be inserted into a SQL Server 2000 table. I am not to use stored procedures. How do I program it? Any help would be appreciated.
Do you have a DataTable ?
You'd need something like:
// set up connection to your database
using (SqlConnection con = new SqlConnection("your-connection-string-here"))
{
// define the INSERT statement - of course, I don't know what your table name
// is and which and how many fields you want to insert - adjust accordingly
string insertStmt =
"INSERT INTO dbo.YourTable(field1, field2, field3) " +
"VALUES(#field1, #field2, #field3)";
// create SqlCommand object
using (SqlCommand cmd = new SqlCommand(insertStmt, con))
{
// set up the parameters - again: I don't know your parameter names
// nor the parameters types - adjust to your needs
cmd.Parameters.Add("#field1", SqlDbType.Int);
cmd.Parameters.Add("#field2", SqlDbType.VarChar, 100);
cmd.Parameters.Add("#field3", SqlDbType.VarChar, 250);
// open connection
con.Open();
// iterate over all the Rows in your data table
foreach (DataRow row in YourDataTable.Rows)
{
// assign the values to the parameters, based on your DataRow
cmd.Parameters["#field1"].Value = Convert.ToInt32(row["columnname1"]);
cmd.Parameters["#field2"].Value = row["columnname2"].ToString();
cmd.Parameters["#field3"].Value = row["columnname3"].ToString();
// call INSERT statement
cmd.ExecuteNonQuery();
}
// close connection
con.Close();
}
}
Of course, this has no error checking whatsoever, you will need to add some of that yourself (try....catch and so on). But basically, that's the way I would do it, if I can't use stored procedures.
use System.Data.SqlClient.SqlCommand
I need to change some primary keys from non-clustered to clustered but I can't drop the constraint because it is referenced from other foreign keys.
How can I find the tables that reference a primary key in the parent table as part of a foreign relation without looping through all tables in the DB? I need to disable the constraints on those, change the PK and re-enable.
Update:
I do not want to use plain SQL to do this but SMO only.
Marc, I know about ForeignKeys by I need something like:
table.PrimaryKey.ForeignKeys (i.e. which tables are referencing my table's primary key)
I just want to avoid looping through all the tables in the database and check the ForeignKeys property on each and every one of them to see if any of them reference my table.(not scalable)
Ok I think I found it.
table.Columns[0].EnumForeignKeys()
or directly
table.EnumForeignKeys()
I was expecting a property instead of a function. I am pretty sure behind the scenes it does what cmsjr suggested.
Using SMO, you could do this:
using Microsoft.SqlServer.Management.Smo;
Server localServer = new Server("your server name");
Database dasecoDB = localServer.Databases["your database name"];
Table table = dasecoDB.Tables["your table name"];
foreach(ForeignKey fk in table.ForeignKeys)
{
Console.WriteLine("Foreign key {0} references table {1} and key {2}", fk.Name, fk.ReferencedTable, fk.ReferencedKey);
}
Marc
This query should work, and could be executed using Database.ExecuteWithResults
Select fk.Table_Name from
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
where PK.Table_Name = 'SomeTable'
e.g.
SqlConnection sqlConnection =
new SqlConnection(#"Integrated Security=SSPI; Data Source=SomeInstance");
Server server = new Server(serverConnection);
Database db = server.Databases["somedatabase"];
DataSet ds = db.ExecuteWithResults(thesqlabove);
You could use the INFORMATION_SCHEMA Views.
INFORMATION_SCHEMA.TABLE_CONSTRAINTS will give you the names of the primary keys on that table.
SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = #TableName
Given the primary key names you can get the referential constraints that use those keys from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
And then the table names by querying INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
Not SMO as such, but given the above you should be able to put together a query that will list the constraints you need to disable.
It doesn't work for me.
Consider the following relations:
Table1 --> master table;
Table2 --> slave table;
Table2.Table1_ID is a foreign key of Table1.ID
Table1.EnumForeignKeys() return null.
Instead I tried with success the DependencyWalker object. The following code list all the tables which dipend from a given collection of tables.
DependencyWalker w = new DependencyWalker(db.Parent);
DependencyTree tree = w.DiscoverDependencies(urns,false);
DependencyCollection depends = w.WalkDependencies(tree);
foreach (DependencyCollectionNode dcn in depends)
{
if (dcn.Urn.Type == "Table")
{
dcn.Urn.GetNameForType("Table");
Console.WriteLine(dcn.Urn.GetNameForType("Table"));
}
}
where "urns" is a collection of table.Urn.
You will have to travel through dependency tree.
Following is the script which use the SMO to generate Create table and insert script.
**
**ServerConnection conn = new ServerConnection( GetConnection() );
Server server = new Server( conn );
Database db = server.Databases[ mDestinationDatabase ];
// Create database script
StringBuilder dbScript = new StringBuilder();
ScriptingOptions dbCreateOptions = new ScriptingOptions();
dbCreateOptions.DriAll = true;
dbCreateOptions.NoCollation = true;
StringCollection coll = db.Script( dbCreateOptions );
foreach( string str in coll )
{
dbScript.Append( str );
dbScript.Append( Environment.NewLine );
}
sqlInsertCommands = dbScript.ToString();
// Create dependency tree
DependencyWalker w = new DependencyWalker(db.Parent);
UrnCollection urnCollection = new UrnCollection();
DataTable table = db.EnumObjects( DatabaseObjectTypes.Table );
string tableName = string.Empty;
foreach( DataRow row in table.Rows )
{
urnCollection.Add( new Urn( ( string )row[ "Urn" ] ) );
}
DependencyTree tree = w.DiscoverDependencies( urnCollection, true );
DependencyCollection depends = w.WalkDependencies(tree);
// walk through the dependency tree and for each table generate create and insert scripts
foreach (DependencyCollectionNode dcn in depends)
{
if (dcn.Urn.Type == "Table")
{
tableName = dcn.Urn.GetNameForType( "Table" );
DataTable dataTableWithData = GetTableWithData( tableName);
ArrayList columnList = new ArrayList();
foreach(DataColumn dataColumn in dataTableWithData.Columns)
{
columnList.Add( dataColumn.ColumnName );
}
sqlInsertCommands = sqlInsertCommands + Environment.NewLine + Environment.NewLine
+ GetCreateTableScript(tableName )
+ Environment.NewLine + Environment.NewLine
+ BuildInsertSQL( columnList, dataTableWithData, tableName );
}
}**
**