Pass stored procedure result into a table variable - stored-procedures

The stored procedure in question is to be called via a SSIS package. This stopped me from using #TempTable. Apparently those can't be used in a SSIS package situation.
So I thought I'd use a table variable instead, but I can't get it to compile in SQL Server Management Studio.
DECLARE #TempTable TABLE
(
OrganisationId INT NOT NULL,
OrganisationName NVARCHAR(120) NULL,
SummaryText NVARCHAR(MAX) NULL,
Url VARCHAR(8000) NULL,
Address1 NVARCHAR(255) NULL,
Address2 NVARCHAR(255) NULL,
Address3 NVARCHAR(255) NULL,
City NVARCHAR(50) NULL,
County NVARCHAR(50) NULL,
Latitude REAL NULL,
Longitude REAL NULL,
Postcode VARCHAR(8) NULL,
LastUpdatedDate DATETIME NULL,
Geocode GEOGRAPHY NULL,
Contact VARCHAR(1000) NULL,
ContactMethodType INT NULL,
rn INT NULL,
);
INSERT INTO #TempTable
EXEC [dbo].[GetServiceOrganisations] #ResultsViewListServices;
INSERT INTO #TempTable
EXEC [dbo].[GetOrganisations] #ResultsViewListOthers;
The error I get in SQL Server Management Studio is a syntax error, here it is:
What is wrong here?

Kudos to Ed Harper for spotting the trailing comma.

SELECT * INTO #MyTempTable
FROM OPENROWSET('SQLNCLI',
'Server=(local)\SQL2008;Trusted_Connection=yes;',
'EXEC stored proc name with params')
Add stored procedure with params

Related

is it a good practice to store the oauth2.0 claim into database

Now I am design the oauth 2.0 refresh access token api, I am store the refresh token info in PostgreSQL 13 database like this:
CREATE TABLE public.oauth2_refresh_token (
id int8 NOT NULL GENERATED ALWAYS AS IDENTITY,
refresh_token varchar NOT NULL,
user_id int8 NOT NULL,
expire_date int8 NOT NULL,
created_by_ip cidr NULL,
created_time int8 NOT NULL,
updated_time int8 NOT NULL,
replaced_by varchar NULL,
revoked_by_ip varchar NULL,
revoked_date varchar NULL,
created_by_ipv6 cidr NULL,
device_id varchar NOT NULL,
app_type int4 NULL,
auth_mode int4 NULL,
CONSTRAINT refresh_token_id_seq PRIMARY KEY (id)
);
Now I want to store the claim into database because when I refresh the access token, I want to use claim to generate the new access token, so that I could select from database by refresh toekn and use the claim to generate the new access token. This is my generate access token function writen using java:
public static String generateTokenByClaim(Claims claims, Date expireDate) {
SecretKey secretKey = new SecretKeySpec(JWT_SIGN_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());
String accessToken = Jwts.builder().setClaims(claims).setExpiration(expireDate).signWith(secretKey).compact();
return accessToken;
}
is it a good idea to store the claim into database? the problem is that if store into database, the claim did not changed in the furture, only use the first generated claim.

Prisma with psql db - incompatible types: text and uuid

I am trying to learn how to use prisma with a psql database.
I'm running into an issue using references where the id is a uuid string.
I have a user model with:
model User {
id String #id #default(dbgenerated("gen_random_uuid()")) #db.Uuid
request Request?
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [id], references: [id])
// I also tried making the relation field userId
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
When I try to migrate this, I get an error that says:
failed to apply cleanly to the shadow database. Error: db error:
ERROR: foreign key constraint "Request_userId_fkey" cannot be
implemented DETAIL: Key columns "userId" and "id" are of incompatible
types: text and uuid.
The prisma documents dont show an example using uuid.
The example they do give has a second parameter in the Profile model which has a userId as an Int. I tried adding this to my Request model (as an int, as a string and as a uuid). None of these worked.
model User {
id Int #id #default(autoincrement())
email String #unique
name String?
role Role #default(USER)
posts Post[]
profile Profile?
}
model Profile {
id Int #id #default(autoincrement())
bio String
user User #relation(fields: [userId], references: [id])
userId Int
}
How can I reference a userId when it is generated using uuid?
This segment of the prisma documentation suggests (if I have understood it correctly), that any of String or Int or enum should work to recognise a uuid:
Relational databases Corresponding database type: PRIMARY KEY
Can be annotated with a #default() value that uses functions to
auto-generate an ID:
autoincrement() cuid() uuid() Can be defined on any scalar field
(String, Int, enum)
When I try adding the pgcrypto extension to psql, I try to run the migration again and get an error that has less verbose messaging, but still similar issue:
Error parsing attribute "#relation": The type of the field id in the
model Request is not matching the type of the referenced field id
in model User.
I have seen this discussion which suggests somehow lying to prisma. I am not clever enough to understand the gist of what the lie is supposed to be or how to do it.
Someone on github suggested using this referencing syntax in the request model:
user User #relation(fields: [userId], references: [id])
userId String #unique #db.Uuid
I tried it as above, and without the #unique flag, but I still get a migration error that says that uuid and text are incompatible references. I can't find a section of the prisma documentation that addresses how to make uuid references compatible with relation models.
fyi: the migration file for the attempt above shows the following:
CREATE TABLE "Request" (
"id" SERIAL NOT NULL,
"userId" UUID NOT NULL,
CONSTRAINT "Request_pkey" PRIMARY KEY ("id")
);
You will have to use the annotation #db.Uuid on the reference column userId, read more about it here.
Example:
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [userId], references: [id])
userId String #db.Uuid
...your other stuff
}
In your Request model is missing the foreign key userId with #db.Uuid this will make postgreSql use the uuid type on a column and #relation the field name must be the same as the foreign key like this #relation(fields: [userId]). The complete code should look like this:
model User {
id String #id #default(dbgenerated("gen_random_uuid()")) #db.Uuid
request Request?
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [userId], references: [id]) <-ADD userId here
userId String #db.Uuid <-ADD THIS
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
You can do this with other types, here are some examples: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#string
I had a similar error and it was because I did not change the type of the relation's ID from Int to String from the example.
If you update the Request model to look like this, does it work?
model Request {
id Int #id #default(autoincrement())
user User #relation(fields: [id], references: [id])
userId String // <- this was missing
createdAt DateTime #default(now()) #db.Timestamptz(6)
updatedAt DateTime #default(now()) #updatedAt #db.Timestamptz(6)
}
I think that the Felix Hagspiel answer is the solution. I could add you should remove the failed generated migration sql (by removing the folder) and retry it again after fixing the problem.

What is the purpose of the OAUTH_CLIENT_TOKEN table in a Spring Oauth2 JDBC implementation

Do you know what is the purpose of the OAUTH_CLIENT_TOKEN table in a JDBC implementation of a Spring Oauth2 server ?
It seems that the table is never populated, however when a client obtains a token using "client credentials", its token is saved into OAUTH_ACCESS_TOKEN and not into OAUTH_CLIENT_TOKEN with a null username.
Here is the tables schemas very similar actually.
drop table if exists oauth_client_token;
create table oauth_client_token
(
token_id VARCHAR(255),
token LONGBLOB,
authentication_id VARCHAR(255),
user_name VARCHAR(255),
client_id VARCHAR(255)
);
drop table if exists oauth_access_token;
create table `oauth_access_token`
(
token_id VARCHAR(255),
token LONGBLOB,
authentication_id VARCHAR(255) PRIMARY KEY,
user_name VARCHAR(255),
client_id VARCHAR(255),
authentication LONGBLOB,
refresh_token VARCHAR(255)
);
Also the configuration into the AuthorizationServerConfigurerAdapter
#Bean
public JdbcClientTokenServices clientTokenServices() {
return new JdbcClientTokenServices(this.dataSource);
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(this.dataSource);
}
That table doesn't seem to be used anymore. The legacy Spring oauth2 authorization server will reach end of live in may 22.

why to use select statement even though inserting values in sql server database,using entity framework MVC application

I am very new to the MVC,Entity framework application and am still learning. I have a query.
I am inserting the values in SQL server database using Entity Framework and MVC application with the stored procedure. I am using the DB first approach. I want to ask why I need to add an select statement even though I have written the procedure to insert the values. If I dont write the select statement then it throws the error.
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: The data reader is incompatible with the specified 'EmployeeDBModel.Employee'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name.
ALTER PROCEDURE [dbo].[sp_InsertEmployees]
-- Add the parameters for the stored procedure here
#FirstName varchar(50),
#LastName varchar(50),
#Address varchar(50),
#Salary int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Insert into Employee values(#FirstName,#LastName,#Address,#Salary)
--select scope_identity() as Id,Firstname,LastName,Address,Salary from Employee
END
If I uncomment select command it just work.
Note:- Id is identity column and auto seed is true
Model :-
public partial class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public Nullable<int> Salary { get; set; }
}
Controller:
[HttpPost]
public ActionResult Create(Employee emp)
{
using (EmployeeDBEntities db = new EmployeeDBEntities())
{
if (ModelState.IsValid)
{
db.InsertEmpDetail(emp.FirstName, emp.LastName, emp.Address, emp.Salary);
db.SaveChanges();
ViewBag.Message = "New Employee Created Successfully!!";
}
}
return View(emp);
}
I have created the function InsertEmpDetail and mapped it properly.
I think if I dont remember it wrongly , when you map you entity, the orm entity framework will need to be able to read for the entity through certaion way. (sorry cant get to my net computer, but in java it often the same).
I'm guessing that your procedure have return result thus the will be read onto the entity.
another possibililty is the commit of the stored procedure, since it cant be read after insert properly, the column seems to be missing.
(just saying this have happen to me before)
good luck,
edd

SubmitChanges doesn't always update database

I am using ASP.NET MVC 4 (.NET framework 4.5) with LINQ-to-SQL and SQL Server 2008 R2
This function returns always true if I run it through debug mode, but when I run it without debug, it returns false. I once got this error: http://i.imgur.com/HydhT.png
I tried googling this, some similiar problems came up but I checked them all:
UserProfiles table has a primary key
The datacontext is in sync with the database
I've tried putting ConflictMode.ContinueOnConflict as an argument in SubmitChanges()
I've tried to put above the facebookID in LINQ designer: UpdateCheck=UpdateCheck.Never
Nothing works. I have never experienced anything like this before. Does anyone have any idea?
Code:
facebookID field in SQL Server is varchar(50) NULL with default value NULL
public static bool changeFacebookIDByEmail(string email, string facebookID)
{
UserProfile profile = (from s in _dc.Users
join u in _dc.Memberships on s.UserId equals u.UserId
join i in _dc.UserProfiles on u.UserId equals i.userID
where u.Email == email
select i).SingleOrDefault();
profile.facebookID = facebookID;
ChangeSet cs = _dc.GetChangeSet();
_dc.SubmitChanges();
if (cs.Updates.Count <= 0)
return false;
else
return true;
}
It seems like you are executing a manual SQL statement:
UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'
This will set the facebookID to null. Entity framework does not know this, though. It cannot interpret raw SQL. So it still thinks the facebookID is set to some value. When you later set it to that value in changeFacebookIDByEmail EF thinks nothing changed.
Sou you probably should not execute raw SQL strings. Use EF to change the value to null.
Change .singleordefault to .single I think your problem will be revealed pretty soon after that.
Basically anything found by your query with be in the datacontext. Anything new eg default will not.
You need to rewrite your routine to insert the new user in the case where it's not found.
EDIT
This is some code from a project I have been working on. I've cut out a bunch of stuff to demonstrate how it should work.
// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);
if (found == null)
{
found = new Identity
{
Domain = domain,
Password = User.Identity.AuthenticationType,
Salt = "",
UserName = userName,
LastUpdatedDateTime = DateTime.Now
};
dB.Identities.InsertOnSubmit(found);
}
dB.SubmitChanges(null);

Resources