How to insert nvarchar value in a query string - sql

I have a query string which is
var projectid = sqlConn.Query<int>("insert into project (name,customer_id, service_id,user_id) values (#name,#customerid,#serviceid,#userid);SELECT SCOPE_IDENTITY(); ", new { name = Name, customerid = Customer, serviceid = Service, userid = userId }).Single();
where name is a nvarchar field. Now I know I need to use 'N' character and I have tried the followings
'N#name'
N'#name'
but it doesn't seem to work. Can anyone help me with this please?

You don't need to use N prefix with variables.
It is needed only with explicitly typed strings (string constants) like insert into ... values(N'some text', ...)
If your name variable contains unicode string - then no special actions are required.

Related

Pandas read_sql_query with parameters for a string with no quotes

I have want to insert a string of identifiers into a piece of sql code using
df = pd.read_sql_query(query, self.connection,params=sql_parameter)
my parameter dictionary looks like this
sql_parameter = {'itemids':itemids_str}
where itemids_str is a string like
282940499, 276686324, 2665846, 46875436, 530272885, 2590230, 557021480, 282937154, 46259344
The SQL code looks like
SELECT
xxx,
yyy,
zzz
FROM tablexyz
where some_column_name in ( %(itemids)s )
My current code gets my the parameter inserted with its quotes
where some_column_name in ( '282940499, 276686324, 2665846, 46875436, 530272885, 2590230, 557021480, 282937154, 46259344' )
How can I prevent the string being inserted including the ', these are not part of my string, but I assume they come from the parameter type string when using %s
I don't think there is a provision in params to send a list of numeric values for one condition. I always add such condition directly to the query
item_ids = [str(item_id) for item_id in item_ids]
where_str = ','.join(item_ids)
query = f"""SELECT
xxx,
yyy,
zzz
FROM tablexyz
where some_column_name in ({where_str})"""

Select Specific Column from a Linked Server Table

I have the following C# code to select a column from a table that is on a linked server:
var query2 = $#"select [FileName] from [AMS_H2H].[H2H].[dbo].[FileReconciliation] where ProductCode = #productCode";
LayZConnection(); //make the db connection
var candidates = _dbConnection.Query<int>(query2, new { productCode = "ACHDH" });
When running it, I get the following error:
"Input string was not in a correct format."
If my query is instead the following, where I select all columns, it works:
var query2 = $#"select * from [AMS_H2H].[H2H].[dbo].[FileReconciliation]
What is the correct format to select just the FileName. Btw, the first query works fine from MSSMS.
You're specifying a type of int in Query<int>, which will cause Dapper to try and map the result of the query to an integer, however your query is returning a filename in select [FileName], which would suggest that it is a string.
Changing the type Query<string> should solve the issue.
More information on Dapper's Query method is available in Dapper's documentation

How to use where in list items

I have a database as below:
TABLE_B:
ID Name LISTID
1 NameB1 1
2 NameB2 1,10
3 NameB3 1025,1026
To select list data of table with ID. I used:
public static List<ListData> GetDataById(string id)
{
var db = Connect.GetDataContext<DataContext>("NameConnection");
var sql = (from tblB in db.TABLE_B
where tblB.LISTID.Contains(id)
select new ListData
{
Name= tblB.Name,
});
return sql.ToList();
}
When I call the function:
GetDataById("10") ==> Data return "NameB2, NameB3" are not correct.
The data correct is "NameB2". Please help me about that?
Thanks!
The value 10 will cause unintended matches because LISTID is a string/varchar type, as you already saw, and the Contains function does not know that there delimiters that should be taken into account.
The fix could be very simple: surround both the id that you are looking for and LISTID with extra commas.
So you will now be looking for ,10,.
The value ,10, will be found in ,1,10, and not in ,1025,1026,
The LINQ where clause then becomes this:
where ("," + tblB.LISTID + ",").Contains("," + id + ",")

Update all rows where contains 5 keys

I have Ticket table that has some columns like this :
ID : int
Body : nvarchar
Type : int
I have many rows where the Body column has value like this :
IPAddress = sometext, ComputerName = sometext , GetID = sometext, CustomerName=sometext-sometext , PharmacyCode = 13162900
I want update all rows' Type column where the Body column has at least five of the following keys:
IPAddress, ComputerName, GetID, CustomerName, PharmacyCode
You could do it with a simple update statement like that
UPDATE Ticket
SET Type = 4
WHERE Body LIKE '%IPAddress%'
and Body LIKE '%ComputerName%'
and Body LIKE '%GetID%'
and Body LIKE '%CustomerName%'
and Body LIKE '%PharmacyCode%'
if you know the 'keys' are always in the same order you could concatenate the LIKE conditions like so
UPDATE Ticket
SET Type = 4
WHERE Body LIKE '%IPAddress%ComputerName%GetID%CustomerName%PharmacyCode%'
If you have the possibility to change the data model it would be much better to explode this key & value column into an own table and link it back to this table as it is done in a proper relational model.
If you could calculate number of key value pair by number of = present in your string you could use this query
Update tblname set col=val where len(colname) - len(replace(colname,'=','')>5
The where part actually gives number of equal signs present in your string.

SQL attribute name in parameterized query

I am using following function for retrieving record on choice. I gave table my column name and value and it shows the result. but the problem is, Its not getting column name as parameter like:
public List<Products> ListAllProducts(string searchOption, string searchValue)
{
db.ClearParameters();
db.AddParameter(db.MakeInParam("#ColumnName", DbType.String, 50, searchOption));
db.AddParameter(db.MakeInParam("#Value", DbType.String, 50, searchValue));
string query = #"SELECT *
FROM [Products]
WHERE #ColumnName LIKE '%'+#Value+'%'";
ds = db.GetDataSet(query);
//Rest of code but above query is not executing
}
but when I use query like this:
string query = #"SELECT *
FROM [Products]
WHERE "+searchOption+" LIKE '%'+#Value+'%'";
It runs fine and give me result. I read this, this and this one specially, but got no idea.
Kindly guide me.
Parameters can be used in place of values inside expressions, and for nothing else: in particular, you cannot use parameters to denote table names, column names, sort order specifiers, or other parts of SQL statement that are not values.
Your non-parametersized query works, because searchOption is copied into your SQL, and becomes part of the query string.
If you need to build a query that changes conditions based on a parameter, you need to change the condition to account for all possible values of #ColumnName, like this
string query = #"SELECT *
FROM [Products]
WHERE (#ColumnName='FirstName' AND FirstName LIKE '%'+#Value+'%')
OR (#ColumnName='LastName' AND LastName LIKE '%'+#Value+'%')
OR (#ColumnName='Location' AND Location LIKE '%'+#Value+'%')";
or fall back on generating your query dynamically. As long as searchOption is not coming from user's input directly, you are safe from SQL injection attacks even though your SQL is generated dynamically.
While Trying, I came across following option and posted in answer ,so other may get benifit of this.
string query = String.Format(
#"SELECT *
FROM [Products]
WHERE {0} LIKE '%'+#Value+'%'", searchOption
);
So the complete function becomes:
public List<Products> ListAllProducts(string searchOption, string searchValue)
{
db.ClearParameters();
db.AddParameter(db.MakeInParam("#Value", DbType.String, 50, searchValue));
string query = String.Format(
#"SELECT *
FROM [Products]
WHERE {0} LIKE '%'+#Value+'%'", searchOption
);
ds = db.GetDataSet(query);
//Rest of code
}