How to pass variable to update query with linked server which is having xml column - linked-server

How can we pass an integer variable in where clause for the following update query?
Declare #ID int = 2
UPDATE t SET Name = 'assaaa' FROM Openquery([Servername], 'SELECT Name,convert(nvarchar(MAX), Resume) FROM [DB].[dbo].[RRtest] where Id ='+#ID+'')t
Please help.

I found the solution, this worked for me :
Declare #ID int =2
UPDATE s SET Name = 'et' FROM Openquery([Servername], 'SELECT ID,Name,convert(nvarchar(MAX), XMLcolumn1) FROM [DB].[dbo].[Table]')s where id = #ID

Related

JDBC - SQLITE Select to variable

I am trying to run a query / select statement and save it in a variable. I know how to get something specific from a specific column but not from counting rows.
This is working as I getting MYID specifically.
ResultSet MYIDrs = stmtCFG.executeQuery( "SELECT rowid, MYID from MYINDEX order by rowid desc limit 1;" );
MYID = MYIDrs.getString("MYID");
Now I am trying to count the rows that works in SQLite client but not in the jdbc as I can't figure out what to request.
this is what I have but is not resulting in what I am expecting.
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString(?????);
problem or question is: What do I put in the ????? as I already tried everything.
I am expecting to see a number.
I am really sorry I found what I was looking for by assigning a name TOTAL
This is my code and it works...
ResultSet FILE_COUNTrs = stmtCFG.executeQuery( "SELECT count(*) AS TOTAL from TABLE where MYID = '"+MYID+"';");
FILE_COUNT = FILE_COUNTrs.getString("TOTAL");
You use wrong data type. COUNT(*) returns Integer type, Not String.
You can do like this without assigning a label for COUNT(*)
int FILE_COUNT = FILE_COUNTrs.getInt(1); // 1: is the column index of COUNT(*)

Pass parameter that will return all rows

I'm working on an ASP.NET application that will call a simple Stored Procedure. The SP looks something like this:
Select *
from empTable
where ID = #ID AND Department = #DeptID
and status = #status
and role = #role
The ASP.NET application will pass a value to the each parameter in the stored procedure. Every parameter can be null or have a value. However, if the user enter nothing (null or empty), it should return everything in that empTable as if Select * from empTable with no Where clause.
However, due to the orders from the management:
I CANNOT change the code in ASP.NET application.
I CANNOT use dynamic SQL.
I'm only allowed to modify the stored procedure.
Is there any way I can work around this?
Make the parameter optional by changing the WHERE clause and assign a default value.
CREATE PROCEDURE MyProc
#ID INT = NULL
AS
Select * from empTable where ID = ISNULL(#ID, ID);
Case statements work...use case to set 1 = 1 when #id = 'all' (or whatever you want the #id to equal for all)
Select * from empTable where
case when #id = 'all' then 1 else id end
=
case when #id = 'all' then 1 else #id
JodyT's answer is better...this works, but not as pretty

How to autogenerate the username with specific string?

I am using asp.net2008 and MY SQL.
I want to auto-generate the value for the field username with the format as
"SISI001", "SISI002",
etc. in SQL whenever the new record is going to inserted.
How can i do it?
What can be the SQL query ?
Thanks.
Add a column with auto increment integer data type
Then get the maximum value of that column in the table using "Max()" function and assign the value to a integer variable (let the variable be 'x').
After that
string userid = "SISI";
x=x+1;
string count = new string('0',6-x.ToString().length);
userid=userid+count+x.ToString();
Use userid as your username
Hope It Helps. Good Luck.
PLAN A>
You need to keep a table (keys) that contains the last numeric ID generated for various entities. This case the entity is "user". So the table will contain two cols viz. entity varchar(100) and lastid int.
You can then have a function written that will receive the entity name and return the incremented ID. Use this ID concatenated with the string component "SISI" to be passed to MySQL for insertion to the database.
Following is the MySQL Table tblkeys:
CREATE TABLE `tblkeys` (
`entity` varchar(100) NOT NULL,
`lastid` int(11) NOT NULL,
PRIMARY KEY (`entity`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The MySQL Function:
DELIMITER $$
CREATE FUNCTION `getkey`( ps_entity VARCHAR(100)) RETURNS INT(11)
BEGIN
DECLARE ll_lastid INT;
UPDATE tblkeys SET lastid = lastid+1 WHERE tblkeys.entity = ps_entity;
SELECT tblkeys.lastid INTO ll_lastid FROM tblkeys WHERE tblkeys.entity = ps_entity;
RETURN ll_lastid;
END$$
DELIMITER ;
The sample function call:
SELECT getkey('user')
Sample Insert command:
insert into users(username, password) values ('SISI'+getkey('user'), '$password')
Plan B>
This way the ID will be a bit larger but will not require any extra table. Use the following SQL to get a new unique ID:
SELECT ROUND(NOW() + 0)
You can pass it as part of the insert command and concatenate it with the string component of "SISI".
I am not an asp.net developer but i can help you
You can do something like this...
create a sequence in your mysql database as-
CREATE SEQUENCE "Database_name"."SEQUENCE1" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 001 START WITH 21 CACHE 20 NOORDER NOCYCLE ;
and then while inserting use this query-----
insert into testing (userName) values(concat('SISI', sequence1.nextval))
may it help you in your doubt...
Try this:
CREATE TABLE Users (
IDs int NOT NULL IDENTITY (1, 1),
USERNAME AS 'SISI' + RIGHT('000000000' + CAST(IDs as varchar(10)), 4), --//getting uniqueness of IDs field
Address varchar(150)
)
(not tested)

SQL - Stored Proc to Update table from Table Variable

I have a stored procedure which inserts records into a table using values from my table variable. (The table variable is sent to SQL from ASP.NET) It works perfect and looks like this...
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
INSERT INTO tbl_Responses
(
assessmentid, questionid, answerid
)
SELECT assessmentid, questionid, answerid
FROM #TableVariable
END
The above inserts one record into tbl_Responses for every row in #TableVariable.
The Problem
Instead of INSERT, I would like to perform an UPDATE, but I can't get the syntax right.
Thanks for any help...!
UPDATE
With some helpful hints, I was able to resolve this below...
You could try this (I haven't tested it) -
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
UPDATE tbl_Responses set questionid = #TableVariable.questionid
FROM #TableVariable
WHERE #TableVariable.assessmentid = tbl_Response.assessmentid
END
Depending on what the join is between the table variable and the table that needs to be updated:
CREATE PROCEDURE sp_SaveResponses
(
#TableVariable SaveResponsesTableType READONLY
)
AS
BEGIN
UPDATE
tbl_Responses
SET
questionid = #TableVariable.questionid
FROM
#TableVariable T1
JOIN tbl_Responses T2 ON T1.assessmentid = T2.assessmentID
END
Thanks to #ipr1010 and #cob666 whose answers led me in the right direction... Here is the solution.
UPDATE tbl_Responses SET answerid = T1.answerid
FROM #TableVariable T1
WHERE tbl_Responses.assessmentid = T1.assessmentid AND tbl_Responses.questionid = T1.questionid
Naming #TableVariable T1 resolved the "must declare scalar variable..." issue.
I also needed to update my WHERE clause or all values were updated with the first value in #TableVariable.
I wish I could vote you guys up but apparently my street cred is too weak!

Cannot implicitly convert type 'System.Data.Linq.ISingleResult<CustomeProcedureName> to 'int'

Sorry for this simple question .
I have a Stored Procedure that return an int value , I'm trying to call this sp from my asp.net linq to sql project .
int currentRating = db.sproc_GetAverageByPageId(pageId);
But i get this error :
Cannot implicitly convert type `'System.Data.Linq.ISingleResult<PsychoDataLayer.sproc_GetAverageByPageId> to 'int' .`
Edit 1
The solution that friends implied didn't work . All the time it return 0
For more information i put my stored procedure here :
ALTER procedure [dbo].[sproc_GetAverageByPageId](
#PageId int )
as
select (select sum(score) from votes where pageId = #PageId)/(select count(*) from votes where pageId=#PageId)
You should inspect the ReturnValue property.
Perhaps the following works better?
int currentRating = (int)db.sproc_GetAverageByPageId(pageId).ReturnValue;
Update: since your stored proc returns a resultset instead of using a return statement the actual data will be available as an element in the enumerable returned by db.sproc_GetAverageByPageId(pageId). If you inspect the ISingleResult<T> type, you'll see that it inherits IEnumerable<T> which indicates that you can enumerate the object to get to the data, each element being of type T.
Since the sproc does a SELECT SUM(*) ... we can count on the resultset to always contain one row. Thus, the following code will give you the first (and only) element in the collection:
var sumRow = db.sproc_GetAverageByPageId(pageId).Single();
Now, the type of sumRow will be T from the interface definition, which in your case is PsychoDataLayer.sproc_GetAverageByPageId. This type hopefully contains a property that contains the actual value you are after.
Perhaps you can share with us the layout of the PsychoDataLayer.sproc_GetAverageByPageId type?
Looks like you're actually after the ReturnValue. You may need to cast it to System.Data.Linq.ISingleResult if it isn't already, then cast ReturnValueto int.
This is actually returning an ISingleResult
int currentRating = (int) db.sproc_GetAverageByPageId(pageId).ReturnValue;
Change your sp to :
ALTER procedure [dbo].[sproc_GetAverageByPageId](
#PageId int )
as
return (select sum(score) from votes where pageId = #PageId)/(select count(*) from votes where pageId=#PageId)
one more thing you can do:
ALTER procedure [dbo].[sproc_GetAverageByPageId](#PageId int ) as
select (select sum(score) from votes where pageId = #PageId)/(SELECT * FROM votes where pageId=#PageId)
WRITE >>
"select * From"<< instead of "select Count(*)"
select (select sum(score) from votes where pageId = #PageId)/(SELECT * FROM votes where pageId=#PageId)
and after that:
int currentRating = (int)db.sproc_GetAverageByPageId(pageId).count();

Resources