INSERT OR REPLACE messing with ID SQLite - sql

My app works like this, I have a local database that is filled with data that comes from my API, and when I have a new data inserted in my API the app checks for the last modified item and synchronize it, and in order to achieve that I'm using INSERT OR REPLACE statement, but it is messing up with my "faturamento_id", it is deleting the ids and replacing with new ones, I want it to continue auto increment(if it is possible) when there is new data to synchronize. How can I do that?
angular.forEach(item.faturamentos, function (fat) {
db.transaction(
function (tx) {
tx.executeSql('INSERT OR REPLACE INTO faturamento_pedidos (valor_a_faturar, ' +
'nota_fiscal, ' +
'_criado,' +
'_modificado , ' +
'_status, ' +
'id_rm, ' +
'cod_id, ' +
'id_rm_pedido, ' +
'id_rm_empresa, ' +
'data, ' +
'informacoes_adicionais ) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
[
fat.valor_a_faturar,
fat.nota_fiscal,
fat.criado,
fat.modificado,
fat.status,
fat.id,
fat.cod_id,
fat.id_rm_pedido,
fat.id_rm_empresa,
fat.data,
fat.informacoes_adicionais
]);
},
txErrorHandler,
function () {
log('Record inserted successfully');
}
);
});
TABLE:
tx.executeSql("CREATE TABLE IF NOT EXISTS faturamento_pedidos (" +
"faturamento_id Integer PRIMARY KEY AUTOINCREMENT, " +
"_criado Text, " +
"_modificado Text, " +
"_status Text, " +
"id_rm Integer, " +
"id_rm_pedido Integer, " +
"id_rm_empresa Integer, " +
"cod_id Text, " +
"valor_a_faturar Text, " +
"nota_fiscal Text, " +
"data Text, " +
"informacoes_adicionais Text," +
"CONSTRAINT unique_id_rm UNIQUE ('id_rm'))");
tx.executeSql('CREATE INDEX IF NOT EXISTS "faturamento_pedidos.index_faturamento_id" ON "faturamento_pedidos"("faturamento_id");');

INSERT OR REPLACE always removes the old row, if it exists.
However, there is no reason to use a single SQL statement.
Just try to update the old row, and if it was not found, you know you have to insert a new one:
tx.executeSql("UPDATE ...",
[...],
function(tx, result) {
if (result.rowsAffected == 0)
tx.executeSql("INSERT ...", [...]);
});

Related

SQL Server - SQL Cascade Change Data Type of a Column

This is a problem as old as the hills, and nearly everyone would have encountered it. So, I'm looking for the most common, and most solid solution.
If I have a primary key column in a table, other tables have foreign keys linked to that column, and I want to change the data type of the column, what is the best tool for achieving this without having to write ad hoc database scripts manually, and without having to delete data? Is there a tool for this?
So, say for example, I have two tables
Sale
SaleKey (int)
Total (decimal)
SaleLine
SaleLineKey (int)
Sale (int) <- Foreign Key back to Sale
Quantity (int)
Rate (decimal)
Lets say, I want to wholesale change the column SaleKey on Sale to a unique identifier. It means that I've got to write a database script to add the new unique identifier column on Sale, add a similar column on SaleLine, update the data in SaleLine to reflect Sale, drop the foreign and primary keys, then put new foreign and primary keys on. This is all possible but time consuming.
Is there an application out there that will do this for me? Or, a stored proc that someone has already written? SQL Server has cascade delete of data, what about cascade change data type?
This is a solution with C#. You'll have to fill in the blanks in terms of ExecuteScript, and ExecuteScalar, but the logic will work as long as you are using SQL Server. This will only convert to uniqueidentifier, but it would not be hard to change it for a different data type. There are a few assumptions here. For example, this code assumes that the column you are trying to change has a maximum of one primary key. It might be a good project to move this in to an open source repo at some point. Also, this could be easily converted to T/SQL. I'm just better with C# than T/SQL.
Warning: This is destructive code. It will indiscriminately delete indexes and keys etc. So, you must take care when running this to make sure that the resulting columns matched your intended data schema. This is only a tool for achieving the task at hand - not a bulletproof catch all solution. This has been tested fairly thoroughly in our databases though.
public void ChangeColumnDataTypeToUniqueIdentifier(string schemaName, string tableName, string columnName, bool allowsNull, ConnectionInfo connectionInfo)
{
string script = null;
var tempColumnName = $"{columnName}Temp";
var columnDataTypeString = DatabaseAdapter.SqlStatementBuilder.GetSqlDataType(ColumnDataType.UniqueIdentifier, 0, 0, 0);
//Add the temp column
//TODO: We should try to figure out if this needs not null, but we can rely on the schema upgrade to fix this later...
ExecuteScript(connectionInfo,
"alter table " +
$" {schemaName}.{tableName} " +
"add " +
$" {tempColumnName} {columnDataTypeString}");
var fullTableName = $"[{schemaName}].[{tableName}]";
//Update the temp column to new values
//TODO: this contains UniqueIdentifier specific code
ExecuteScript(connectionInfo,
"update " +
$" {fullTableName} " +
"set " +
$" {tempColumnName} = NEWID()");
ExecuteScript(connectionInfo,
"alter table " +
$" {schemaName}.{tableName} " +
"alter column " +
$" {tempColumnName} {columnDataTypeString} {(!allowsNull ? string.Empty : "not")} null");
//Get the schema id of the target table
var targetSchemaObjectId = (int)DatabaseAdapter.ExecuteScalar("select schema_id from sys.schemas where name = #Param1", new Collection<DataParameter> { new DataParameter("Param1", schemaName) }, connectionInfo, null);
//Get the object id of the table we are modifying
var targetTableObjectId = (int)DatabaseAdapter.ExecuteScalar("select object_Id from sys.tables where name = #Param1 and schema_id = #Param2", new Collection<DataParameter> { new DataParameter("Param1", tableName), new DataParameter("Param2", targetSchemaObjectId) }, connectionInfo, null);
//Get foreign keys
using (var foreignKeyData = DatabaseAdapter.ExecuteReader("select * from Sys.foreign_keys where referenced_object_id = #Param1", new Collection<DataParameter> { new DataParameter("Param1", targetTableObjectId) }, connectionInfo, null))
{
//Iterate through foreign keys
while (foreignKeyData.DataReader.Read())
{
//Get thei object id of the table that references this
var tableThatReferencesThisObjectId = (int)foreignKeyData.DataReader["parent_object_Id"];
var foreignKeyObjectId = (int)foreignKeyData.DataReader["object_Id"];
var foreignKeyName = (string)foreignKeyData.DataReader["name"];
//Get the tables data
using (var tableThatReferencesThisData = DatabaseAdapter.ExecuteReader("select * from Sys.tables where object_id = #Param1", new Collection<DataParameter> { new DataParameter("Param1", tableThatReferencesThisObjectId) }, connectionInfo, null))
{
//Read the record
tableThatReferencesThisData.DataReader.Read();
//Get information about the table references this
var tableThatReferencesThisName = (string)tableThatReferencesThisData.DataReader["name"];
var tableThatReferencesShemaObjectId = (int)tableThatReferencesThisData.DataReader["schema_id"];
var tableThatReferencesShemaName = (string)DatabaseAdapter.ExecuteScalar("select * from sys.schemas where schema_id = #Param1", new Collection<DataParameter> { new DataParameter("Param1", tableThatReferencesShemaObjectId) }, connectionInfo, null);
//Get the name of the column that references the original column
var foreignKeyColumnName = (string)DatabaseAdapter.ExecuteScalar
(
"select " +
" COL_NAME(fks.parent_object_id, fkcs.parent_column_id) " +
"from " +
" sys.foreign_keys fks " +
"inner join " +
" Sys.foreign_key_columns fkcs " +
"on " +
" fkcs.constraint_object_id = fks.object_id " +
"where " +
$" fks.object_id = {foreignKeyObjectId}", new Collection<DataParameter> { new DataParameter("Param1", tableThatReferencesShemaObjectId) }, connectionInfo, null);
//The new target temp column name
var tempForeignKeyColumnName = foreignKeyColumnName + "Temp";
//Concatenate the name of the table that references the original table
var tableThatReferencesFullName = $"[{tableThatReferencesShemaName}].[{tableThatReferencesThisName}]";
//Add the temp column
//TODO: We should try to figure out if this needs not null, but we can rely on the schema upgrade to fix this later...
ExecuteScript(connectionInfo,
"alter table " +
$" {tableThatReferencesFullName} " +
"add " +
$" {tempForeignKeyColumnName} uniqueidentifier");
//Update the data in the temp column
script =
"update " +
$" {tableThatReferencesFullName} " +
"set " +
$"{tempForeignKeyColumnName} = " +
" ( " +
" select " +
$" {tempColumnName} " +
" from " +
$" {fullTableName} referencedtable " +
" where " +
$" {tableThatReferencesFullName}.[{foreignKeyColumnName}] = referencedtable.{columnName} " +
" )";
ExecuteScript(connectionInfo, script);
//Drop the original foreign key
script =
"alter table " +
$" {tableThatReferencesFullName} " +
"drop " +
$" {foreignKeyName} ";
ExecuteScript(connectionInfo, script);
DropIndexesForTable(tableThatReferencesShemaName, tableThatReferencesThisName, foreignKeyColumnName, connectionInfo);
//Drop the old column
script =
"alter table " +
$" {tableThatReferencesFullName} " +
"drop column " +
$" [{foreignKeyColumnName}] ";
ExecuteScript(connectionInfo, script);
//Rename the new temp column to the old one
ExecuteScript(connectionInfo, $"EXEC sp_rename '{tableThatReferencesFullName}.{tempForeignKeyColumnName}', '{foreignKeyColumnName}', 'COLUMN'");
}
}
}
var pkName = (string)DatabaseAdapter.ExecuteScalar($"select name from sys.key_constraints where parent_object_id = #Param1 and type = 'PK'", new Collection<DataParameter> { new DataParameter("Param1", targetTableObjectId) }, connectionInfo, null);
if (!string.IsNullOrEmpty(pkName))
{
//Drop the old primary key
script =
"alter table " +
$" {fullTableName} " +
"drop " +
$" {pkName} ";
ExecuteScript(connectionInfo, script);
}
var defaultConstraintName = (string)DatabaseAdapter.ExecuteScalar(
"select " +
" dc.name " +
"FROM " +
" SYS.DEFAULT_CONSTRAINTS dc " +
"inner join " +
" sys.all_columns ac " +
"on " +
" ac.object_id = #ObjectId and " +
" dc.parent_column_id = ac.column_id " +
"where " +
" parent_object_id = #ObjectId and " +
" ac.name = #ColumnName", new Collection<DataParameter> { new DataParameter("ColumnName", columnName), new DataParameter("ObjectId", targetTableObjectId) }, connectionInfo, null);
if (!string.IsNullOrEmpty(defaultConstraintName))
{
//Drop the old primary key
script =
"alter table " +
$" {fullTableName} " +
"drop constraint" +
$" {defaultConstraintName} ";
ExecuteScript(connectionInfo, script);
}
DropIndexesForTable(schemaName, tableName, columnName, connectionInfo);
//Drop the old column
script =
"alter table " +
$" {fullTableName} " +
"drop column " +
$" {columnName}";
ExecuteScript(connectionInfo, script);
//Rename the new column to the old one
ExecuteScript(connectionInfo, $"EXEC sp_rename '{fullTableName}.{tempColumnName}', '{columnName}', 'COLUMN'");
}
private void DropIndexesForTable(string schemaName, string tableName, string columnName, ConnectionInfo connectionInfo)
{
//find indexes dependent on this column
string script = "SELECT " +
" SchemaName = s.name, " +
" TableName = t.name, " +
" IndexName = ind.name " +
"FROM " +
" sys.indexes ind " +
"INNER JOIN " +
" sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id " +
"INNER JOIN " +
" sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id " +
"INNER JOIN " +
" sys.tables t ON ind.object_id = t.object_id " +
"INNER JOIN " +
" sys.schemas s on t.schema_id = s.schema_id " +
"WHERE " +
" ind.is_primary_key = 0 and" +
" s.name = #SchemaName and " +
" t.name = #TableName and " +
" col.name = #ColumnName";
using (var obstructingIndexData = DatabaseAdapter.ExecuteReader(script, new Collection<DataParameter> { new DataParameter("SchemaName", schemaName), new DataParameter("TableName", tableName), new DataParameter("ColumnName", columnName) }, connectionInfo, null))
{
while (obstructingIndexData.DataReader.Read())
{
var indexSchema = obstructingIndexData.DataReader["SchemaName"];
var indexTable = obstructingIndexData.DataReader["TableName"];
var IndexName = obstructingIndexData.DataReader["IndexName"];
ExecuteScript(connectionInfo, $"drop index [{indexSchema}].[{indexTable}].[{IndexName}]");
}
}
}

What is wrong with this SQLite create Statement in AndroidStudio

Can anyone decipher what's wrong with this method? The log says that there's is a syntax error but I'm not able to see it.
Here's the code:
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createTable = "CREATE_TABLE " + MOVIES_DB + "("
+ TITLE + " TEXT, "
+ OVERVIEW + " TEXT, "
+ POSTER_PATH + " TEXT, "
+ RELEASE_DATE + " TEXT, "
+ ORIGINAL_TITLE + " TEXT, "
+ ORIGINAL_LANGUAGE + " TEXT, "
+ BACKDROP_PATH + " TEXT, "
+ ID + " INTEGER PRIMARY KEY, "
+ VOTE_COUNT + " TEXT, "
+ POPULARITY + " TEXT, "
+ VOTE_AVERAGE + " TEXT, "
+ ADULT + " TEXT, "
+ VIDEO + " TEXT, "
+ GENRE_IDS + " TEXT, "
+ HISTORY_USER + " TEXT, "
+ WATCH_LATER + " TEXT, "
+ FAVORITE_FLAG + " INTEGER DEFAULT 0"
+ ")";
sqLiteDatabase.execSQL(createTable);
}
It used to work. I added the FAVORITE_FLAG and now it doesn't run. I also tried with INTEGER NOT NULL DEFAULT 0 after FAVORITE_FLAG
As said by #Juergen D, CREATE TABLE take a space and not and underscore.
Take a look at the CREATE TABLE Documentation for SQLite.
BTW; try to put your id / PK declaration first, as it's the common practice (and more logical)
SQL Fiddle
SQLite (SQL.js) Schema Setup:
CREATE TABLE MOVIES_DB(
"ID" INTEGER PRIMARY KEY,
"TITLE" TEXT,
"OVERVIEW" TEXT,
"POSTER_PATH" TEXT,
"RELEASE_DATE" TEXT,
"ORIGINAL_TITLE" TEXT,
"ORIGINAL_LANGUAGE" TEXT,
"BACKDROP_PATH" TEXT,
"VOTE_COUNT" TEXT,
"POPULARITY" TEXT,
"VOTE_AVERAGE" TEXT,
"ADULT" TEXT,
"VIDEO" TEXT,
"GENRE_IDS" TEXT,
"HISTORY_USER" TEXT,
"WATCH_LATER" TEXT,
"FAVORITE_FLAG" INTEGER DEFAULT 0
);
Insert into MOVIES_DB Values(1,"test","test","test 7",
"test","test 12","test","test","test","test","test",
"test","test","test","test","test",2);
Query 1:
select ID, TITLE, FAVORITE_FLAG from MOVIES_DB
Results:
| ID | TITLE | FAVORITE_FLAG |
|----|-------|---------------|
| 1 | test | 2 |

MS SQL Server (Ver 2008 or above) - How to recreate auto-incremental based in my ID column

I have a table in csv file (with an ID as numeric).
I manually uploaded the information from the file to a SQL Server data table (creating my ID column as numeric).
But, I want to recreate my ID column as autonumeric ID column that continue the number with the latest entry.
Example: the table have the ID 1, 5, 10. I want to recreate the auto-incremental (IDENTITY) ID column (leaving my old ID's) and next row insertion continue with ID 11.
I suppose that doesn't exists a single method to achieve this. But I want to know the steps that I should follow.
Here is a script to give you an idea of one way you can do it.
IF OBJECT_ID('DELETEME.dbo.Tbl') IS NOT NULL
BEGIN
DROP TABLE Tbl
END
IF OBJECT_ID('DELETEME.dbo.stageTbl') IS NOT NULL
BEGIN
DROP TABLE stageTbl
END
CREATE TABLE Tbl (
ID INT
,A CHAR(1)
)
INSERT INTO Tbl VALUES (1,'A'),(2,'B'),(10,'C')
SELECT *
FROM
Tbl
EXEC sp_rename 'DELETEME.dbo.Tbl', 'stageTbl', 'OBJECT'
--renames original table
--create script for the new table
CREATE TABLE Tbl (
ID INT NOT NULL IDENTITY(1,1)
,A CHAR(1)
)
--have to set IDENTITY_INSERT on to insert the ID into an IDENTITY column
SET IDENTITY_INSERT Tbl ON
INSERT INTO Tbl (ID, A)
SELECT ID, A
FROM
stageTbl
SET IDENTITY_INSERT Tbl OFF
DROP TABLE stageTbl
--drops original table
DBCC CHECKIDENT('Tbl', RESEED, 222)
--sets the number you want to with next if you set as 222 the next identity will be 223
INSERT INTO Tbl (A) VALUES ('D')
SELECT *
FROM
Tbl
Basic Steps
Renames original Table (if you want your new table to be the same name as the old, I like to rename first due to auto generated names of constraints etc on the new table)
Create the New table with the Column as an Identity column
Turn on IDENTITY_INSERT
Select all records from the old table into the new one
Turn off IDENTITY_INSERT
You don't have to but you can RESSED the identity to start with whatever number you want otherwise SQL-server will automatically do this based on the greatest ID value.
Drop the original table that you renamed
Thanks to Matt to help me out with the original question.
I want to share a C# method that I used to automate all the necessary steps:
-- Disclaimer: the use of this is my class that connects with MS SQL Server, used to read a SELECT sentence (And returns a DataTable) and Execute SQL Queries, etc. Hope someone could find this code helpfully (AS-IS) --
/// <summary> Recreate an ID with auto-incremental when the table has the ID without this option.
/// <para>Automatically will rename the original table to TABLENAME_TO_DELETE (The process will require copy and recreate the table, then the process will duplicate the information) </para></summary>
/// <param name="strTable">SQL table</param>
/// <param name="strId">ID column</param>
public string recreateIdentityColumn(string strTable, string strId)
{
string strLog = "Table: {0} - ID: {1}".fwFormat(strTable, strId);
string strNewTable = strTable + "_" + fw.rnd(1, 1000).ToString() + fw.rnd(5000, 10000);
DataTable dtTable = this.fillDataTable("SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION, NUMERIC_SCALE " +
"FROM Information_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = '" + strTable + "'");
if (!dtTable.fwHasData()) throw new Exception("The current table '" + strTable + "' doesn't exists");
DataRow[] drIdInfo = dtTable.Select("COLUMN_NAME = '" + strId + "'");
if (!drIdInfo.fwHasData()) throw new Exception("The ID column '" + strId + "' doesn't exists in the table '" + strTable + "'");
string strIdType = "";
string strColumns = "";
strIdType = drIdInfo[0]["DATA_TYPE"].fwEmpty("");
if (strIdType.fwContains("decimal"))
strIdType += "({0}, {1})".fwFormat(drIdInfo[0]["NUMERIC_PRECISION"].ToString(), drIdInfo[0]["NUMERIC_SCALE"].ToString());
strLog += "\r\nID DataType: " + strIdType;
foreach (DataRow drInfo in dtTable.Rows)
strColumns += ",[" + drInfo["COLUMN_NAME"].ToString() + "]";
strId = "[" + strId.TrimStart('[').TrimEnd(']') + "]";
strColumns = strColumns.TrimStart(',');
strLog += "\r\nColumns: " + strColumns;
try
{
// Rule 1: Clone the table (Only the structure)
this.executeQuery("SELECT TOP 0 * INTO " + strNewTable + " FROM " + strTable);
// Rule 2: Remove the ID from the clone table
this.executeQuery("ALTER TABLE " + strNewTable + " DROP COLUMN " + strId);
// Rule 3: Add the ID column with the identity property
this.executeQuery("ALTER TABLE " + strNewTable + " ADD " + strId + " " + strIdType + " IDENTITY(1,1)");
// Rule 4: Allow manual insertion of ID in the identity column
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " ON");
// Rule 5: Copy the rows into the table
int intTotalRows = this.rowCount(strTable);
int intTotalNewRows = this.executeQuery("INSERT INTO " + strNewTable + "(" + strColumns + ") " +
"SELECT " + strColumns + " FROM " + strTable);
strLog += "\r\nOriginal rows {0} - New rows {1}".fwFormat(intTotalRows.ToString(), intTotalNewRows.ToString());
// Rule 6: Return the insertion of identity rows to a normal state
this.executeQuery("SET IDENTITY_INSERT " + strNewTable + " OFF");
// Rule 7: Rename the table with NO IDENTITY as OLD and rename the table with INDENTITY ID as NEW/ACTUAL
this.executeQuery("EXEC sp_rename '" + strTable + "', '" + strTable + "_TO_DELETE', 'OBJECT'");
this.executeQuery("EXEC sp_rename '" + strNewTable + "', '" + strTable + "', 'OBJECT'");
strLog += "\r\nProcess run without problems";
return strLog;
}
catch (Exception ex)
{
strLog += "\r\nException occur";
throw ex;
}
}

SQLite Insert or Replace using angularJS

I'm trying to implement a INSERT OR REPLACE SQL to update the values that come from my API, the problem is, every time that I register a new item in my API and reload the app, it is duplicating all the rows, it is inserting the whole data again, how can I prevent that to happen?
angular.forEach(item.faturamentos, function (fat) {
//debugger
db.transaction(
function (tx) {
tx.executeSql('INSERT OR REPLACE INTO faturamento_pedidos (valor_a_faturar, ' +
'nota_fiscal, ' +
'_criado,' +
'_modificado , ' +
'_status, ' +
'id_rm, ' +
'cod_id, ' +
'id_rm_pedido, ' +
'id_rm_empresa, ' +
'data, ' +
'informacoes_adicionais ) VALUES (?,?,?,?,?,?,?,?,?,?,?)',
[
fat.valor_a_faturar,
fat.nota_fiscal,
fat.criado,
fat.modificado,
fat.status,
fat.id,
fat.cod_id,
fat.id_rm_pedido,
fat.id_rm_empresa,
fat.data,
fat.informacoes_adicionais
]);
},
txErrorHandler,
function () {
log('Record inserted successfully');
}
);
});
TABLE:
tx.executeSql("CREATE TABLE IF NOT EXISTS faturamento_pedidos (" +
"faturamento_id Integer PRIMARY KEY AUTOINCREMENT, " +
"_criado Text, " +
"_modificado Text, " +
"_status Text, " +
"id_rm Integer, " +
"id_rm_pedido Integer, " +
"id_rm_empresa Integer, " +
"cod_id Text, " +
"valor_a_faturar Text, " +
"nota_fiscal Text, " +
"data Text, " +
"informacoes_adicionais Text," +
"CONSTRAINT unique_id_rm UNIQUE ('id_rm'))");
tx.executeSql('CREATE INDEX IF NOT EXISTS "faturamento_pedidos.index_faturamento_id" ON "faturamento_pedidos"("faturamento_id");');

'IN' query in fusion table

In the following code, i want to add "IN" +Village+. Where to add this condition in the code. Variable village takes value from a drop down list based on that filter should occur.please help me.Village name is a column in my fusion table.
i.e select 'geometry',villageName from table where querypass > textvalue IN villagename='madurai'
function querymape()
{
/*variable holds the value*/
var village =document.getElementById('village').value.replace(/'/g, "\\'");
var operatore=document.getElementById('operatorstringe').value.replace(/'/g, "\\'");
var textvaluee=document.getElementById("text-valuee").value.replace(/'/g, "\\'");
var querypasse=document.getElementById('query-passe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypasse + " FROM " + tableid + " WHERE " + querypasse + " " + operatore + " '" + textvaluee + "'"+"AND 'VillageName=+village+'");
}
}
/*This is my new code.But its not working.Please help me*/
function querymap()
{
//var villagename='';
var operator=document.getElementById('operatorstring').value.replace(/'/g, "\\'");
var textvalue=document.getElementById("text-value").value.replace(/'/g, "\\'");
var querypass=document.getElementById('query-pass').value.replace(/'/g, "\\'");
var searchStringe = document.getElementById('Search-stringe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypass + " FROM " + tableid + " WHERE " + querypass + " " + operator + " '" + textvalue + "'"+"AND 'VillageName'="+ searchStringe+"");
}
}
Multiple conditions can be combined using the keyword "and"?
You twisted the IN syntax around, it is used when you want to match several values, if you only want to compare to a single value use "=" instead
Applied to your query (with IN syntax):
select 'geometry',villageName from table where querypass > textvalue and villagename IN ('madurai','another village')
With = syntax:
select 'geometry',villageName from table where querypass > textvalue and villagename = 'madurai'