Storing the value of ENCRYPTBYPASSPHRASE() - sql-server

I am using the below query in SQL Server Management Studio 2017.
SELECT ENCRYPTBYPASSPHRASE('xxyy','test#123')
When I run the above statement, it returned an encrypted password like 0x01000000EA686E7D1AED8C501B193A2F655368FC3EABA009082C90F58987DD0487833C62
I wanted to store this in a table which contains a NVARCHAR(MAX) field using a stored procedure, but insertion happens with a blank value instead of the encrypted password.
I used a print statement to acquire the value emitted by this function with in the SP. It returned some unreadable characters as below.
됏㬷病譽快
How to use ENCRYPTBYPASSPHRASE() properly in order to insert the return value to a table field.

You can try the following Sql statement
CREATE TABLE #TempPassword (encPassword varbinary(250))
declare #encPwd varbinary(250)
set #encPwd = (SELECT ENCRYPTBYPASSPHRASE('xxyy','test#123'))
insert into #TempPassword values (#encPwd)
select * from #TempPassword
Now the output after insert it is as shown below
encPassword
0x0100000023C4E9BFBC0F4319735ED2F0C76C2D857C114D96867711F1EE290AB2E7511961

Related

Snowflake: Execution error in store procedure : SQL compilation error: Object does not exist or not authorized. At Statement.execute

I'm totally confused by the permission model of the Snowflake system. I created a database, created a stored procedure within that database, and tried to call that stored procedure all with the same user in the SYSADMIN role. I get the error "Execution error in store procedure: SQL compilation error: Object does not exist or not authorized. At Statement.execute"
I'm not even sure where to start. How does my user not have permission to a table that was created by said user?
Check the casing of the name of the objects you are referring to. If you for example created the table wrapped in double quotes, it's case sensitive. Snowflake automatically converts unquoted identifiers to UPPER case.
Example:
CREATE TABLE test1 (
test nvarchar)
CREATE TABLE "teSt2" (
test nvarchar)
-- This works
select * from test1
-- This doesn't work because the table was created wrapped in double quotes and with a capital S in the name
select * from test2
-- This doesn't work either because it will convert to UPPER
select * from teSt2
-- This works
select * from "teSt2"
A stored procedure returns a single row that contains a single column; it is not designed to return a result set. However, if your result set is small enough to fit into a single value of type VARIANT or ARRAY, you can return a result set from a stored procedure with some additional code- here
Hope this helps!
It works for delete statement! Example below:
use role sysadmin;
create or replace database DATA_IMPORTS_SO;
create or replace table ProductMaster_SO (id integer, name varchar);
insert into ProductMaster_SO values (1,'stackoverflow');
insert into ProductMaster_SO values (2,'stackoverflow');
select count(*) FROM DATA_IMPORTS_SO.PUBLIC.ProductMaster_SO;--2 rows
create or replace procedure Clenup_DI_Products()
returns string not null
language javascript
EXECUTE AS OWNER
as
$$
var sql_command =
"delete FROM DATA_IMPORTS_SO.PUBLIC.ProductMaster_SO";
try {
snowflake.execute (
{sqlText: sql_command}
);
return "Succeeded."; // Return a success/error indicator.
}
catch (err) {
return "Failed: " + err; // Return a success/error indicator.
}
$$;
call Clenup_DI_Products();
select count(*) FROM DATA_IMPORTS_SO.PUBLIC.ProductMaster_SO;--0 rows
Ultimately I was unable to find a reason that the stored procedure wouldn't work. I ended up dropping the table and recreating it with an all caps name. After that I was able to run the stored procedure with no issues.
I'm unclear if the fix was creating the table with a UCASE name or recreating it with a USER ROLE SYSADMIN command.
It may not be a problem with the case sensitivity of the table but it might be related to the rights of the stored procedure (Function) you created.
Changing your code as below might do the trick.
EXECUTE AS OWNER -- Present
EXECUTE AS CALLER -- Change
To understand more on owner's rights and caller's right of the Stored Procedure, please follow below link.
https://docs.snowflake.com/en/sql-reference/stored-procedures-rights.html
Two things to check.
Enclose the table name in double-quotes. Check case.
GRANT SELECT ON ALL TABLES IN SCHEMA "SCHEMA_NAME" TO ROLE PUBLIC;

My stored procedure in SQL Server 2008 when is execute with JOB its fails, but without its working great

I have this stored procedure wich its like this :
ALTER PROCEDURE [dbo].[P_ALIMENTATION_VolumeVentes]
AS
BEGIN
SELECT EDS, NomEDS,AgenceEDS, AgenceNomEDS,SecteurEDS, SecteurNomEDS,DirectionEDS,DirectionNomEDS,
(SELECT count(*) FROM CPListeVentesNonConformes WHERE CPListeVentesNonConformes.EDS = CPRT.EDS AND TypePart='PP') AS ListeVenteNC_PP,
(SELECT count(*) FROM CEListeVentesNonConformes WHERE CEListeVentesNonConformes.EDS = CPRT.EDS AND TypePart='ET') AS ListeVenteNC_ET,
(SELECT count(*) FROM CPListeVentesNonConformes WHERE CPListeVentesNonConformes.EDS = CPRT.EDS AND TypePart='PP' OR TypePart='ET') AS ListeVenteNC_PPET,
(SELECT count(*) FROM ListeVentes WHERE IDES01 = CPRT.EDS AND TypePart='PP') AS ListeVentes
INTO VolumeVentes
FROM CPR CPRT
GROUP BY EDS, NomEDS,AgenceEDS, AgenceNomEDS,SecteurEDS, SecteurNomEDS,DirectionEDS,DirectionNomEDS,TypePart
END
When i execute with the command line EXEC [dbo].[P_ALIMENTATION_VolumeVentes]
that work super great my table is create.
But when i use SQL Agent to schedule a job i have a nice surprise to have this error :
Executed as user: ZRES\CSAPREP10IUCRADM. The conversion of a varchar
data type to a datetime data type resulted in an out-of-range value.
[SQLSTATE 22007] (Error 242) The statement has been terminated.
[SQLSTATE 01000] (Error 3621). The step failed.
The structure table who will be create VolumetVentes have no fields with a type as datetime
Here is the structure of the tableVolumeVentes
I don't understand exactly where is the error ?
Thank you for help
Actually it should never work since you already have VolumeVente table.
SELECT INTO creates new table with columns described in select statement
https://msdn.microsoft.com/en-us/library/ms188029(v=sql.120).aspx
You should modify this code to become INSERT SELECT.
But you will probably still get the same conversion error because (I guess) column order is not correct in select statment and does not match column order in existing table. That is why you should always explicitly define column list in INSERT INTO clause, so the final script will look like:
INSERT INTO VolumeVentes(EDS, NomEDS,AgenceEDS, AgenceNomEDS,SecteurEDS, ...)
SELECT EDS, NomEDS,AgenceEDS, AgenceNomEDS,SecteurEDS
FROM ...
Use
INSERT INTO... Statement
instead of
SELECT INTO FROM... Statement

Dynamic SQL Insert: Column name or number of supplied values does not match table definition

I encounter some strange behavior with a dynamic SQL Query.
In a stored procedure I construct an insert query string out of multiple Strings. I execute the insert query in the SP like that - due to single nvarchar length restrictions.
EXEC(#QuerySelectPT+#QueryFromPT+#QueryFromPT)
If I print each part of the query, put these parts together and execute them manually in Management Studio the query works fine and inserts the data. But, if i execute the query in the EXEC() Method in the stored procedure, I get a
Column name or number of supplied values does not match table definition.
Error Message.
Did multiple check on the amount, spelling of columns in my query and in my insert table, but I have not found any differences so far.
Any advices?
Your count of columns for insert are different from count of columns for select. Print the statement before exec and find the error.
It as shot in the dark but seen you are telling the queries are valid and if you build the final query manually and it is working, the issue could be caused by string truncation.
Could you try:
EXEC(CAST(#QuerySelectPT AS VARCHAR(MAX))+#QueryFromPT+#QueryFromPT);
Also, as the Management Studio's message tab and selects are limited to 4000 symbols I think, you can test if the whole query is assembled correctly like this:
SELECT CAST(#QuerySelectPT+#QueryFromPT+#QueryFromPT AS XML)

SQL Server insert or query between servers ingnores column in table starting with a number?

I am trying to query between two servers which have identical tables (used the same create statement for both). When I try to insert the results from Server A to Server B I get an error indicating "Column name or number of supplied values does not match table definition."
Query run on server A
Insert into ServerB.Database1.dbo.Table1
Select *
from Table1
The error is clear, but what isn't clear is the reason that it is generated. The definitions of the two tables are identical. What I was finally able to isolate was a table name that starts with a numeric value is not being recognized.
When I run this on ServerA:
Select *
from ServerB.Database1.dbo.Table1
The field with the numeric value is not shown in the results set of they query. The short term fix was to rename the field in the database, but why is this happening?
I am curious about the collation too, but really the answer is to wrap the object names in square brackets. i.e. SELECT [1col], [2col], [etc] FROM [1database].[2owner].[3table]. This way SQL with recognize each as an object name and not a function.
One other thing to keep in mind is to not use splat (*) in your select statement, this has potential problem of it's own. For example, you could run into an error in your Insert if the ServerA's table1 structure was change and ServerB's table one stayed the same.

DataAdapter Update() requires input parameter for Auto increment primary key column

While updating a DataTable to a SQL Server database I get the error message "Column 'PK_Column' does not allow nulls" after calling GetErrors()
I don't want to provide a value for PK_Column because it is a auto increment primary key column in the database. My insert statement looks like this:
INSERT INTO [Order] ([Customer_Id], [OrderTime], [OrderType])
VALUES(#Customer_Id, #OrderTime, #OrderType)
SELECT CAST(SCOPE_IDENTITY() AS int) AS '#PK_Column'
It works as expected in SQL Server Management Studio, so the query is obviously not the problem.
I have four parameters on the insert command, one output parameter (#PK_Column) and three input parameters (#Customer_Id, #OrderTime, #OrderType). I figured out that I don't get the error if I set #PK_Column to InputOutput parameter, but then the PK_Column value does not get updated with the correct value created by the database.
Try
SELECT #PK_Column = SCOPE_IDENTITY()
This way, you assign to the local variable #PK_Column, which is picked up as a parameter.
When you do ... AS '#PK_Column', you are creating a data set with one column called "#PK_Column", when you want to assign a value to local var/parameter #PK_Column
Note: ... AS #PK_Column would fail because this is column alias. You're relying on a setting that allows '#PK_Column' to be a valid alias where as #PK_Column would fail

Resources