Snowflake Pandas connection issue - snowflake-cloud-data-platform

I'm trying to insert a dataframe into a snowflake table using the pandas connector and am getting permission issues, but using the "normal" snowflake connector works fine.
import snowflake.connector as snow
from snowflake.connector.pandas_tools import *
cur = self.conn.cursor()
my_schema = "my_schema"
my_table = "my_table"
cur.execute(f"""INSERT INTO {my_schema}.{my_table}(load_date, some_id)
values (current_timestamp, 'xxx')""")
write_pandas(self.conn, daily_epc_df, table_name=my_table, schema=my_schema)
But I'm getting
File "/Users/abohr/virtualenv/peak38/lib/python3.8/site-packages/snowflake/connector/errors.py", line 85, in default_errorhandler
raise error_class(
snowflake.connector.errors.ProgrammingError: 001757 (42601): SQL compilation error:
Table '"my_schema"."my_table"' does not exist
the same connection can insert and then doesn't work on the same table.
I also tried
df.to_sql(..., method=pd_writer)
and get
pandas.io.sql.DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting
Why is it talking about sqlite_master if I'm trying to connect to Snowflake? Do the pandas functions require different connections?
my libs:
name = "snowflake-connector-python"
version = "2.3.3"
description = "Snowflake Connector for Python"
category = "main"
optional = false
python-versions = ">=3.5"
[[package]]
name = "pandas"
version = "1.0.5"
description = "Powerful data structures for data analysis, time series, and statistics"
category = "main"
optional = false
python-versions = ">=3.6.1"```
on Python 3.8

I found my issue - I added quote_identifiers=False to
write_pandas(self.conn, daily_epc_df, table_name=my_table, schema=my_schema, quote_identifiers=False)
and now it works.
But seems very wrong that the default behavior would break, I'm still suspicious.

Hmm I've done something superior I think to pandas ...
Tell me if you agree ...
CREATE OR REPLACE PROCEDURE DEMO_DB.PUBLIC.SNOWBALL(
db_name STRING,
schema_name STRING,
snowball_table STRING,
max_age_days FLOAT,
limit FLOAT
)
RETURNS VARIANT
LANGUAGE JAVASCRIPT
COMMENT = 'Collects table and column stats.'
EXECUTE AS OWNER
AS
$$
var validLimit = Math.max(LIMIT, 0); // prevent SQL syntax error caused by negative numbers
var sqlGenerateInserts = `
WITH snowball_tables AS (
SELECT CONCAT_WS('.', table_catalog, table_schema, table_name) AS full_table_name, *
FROM IDENTIFIER(?) -- <<DB_NAME>>.INFORMATION_SCHEMA.TABLES
),
snowball_columns AS (
SELECT CONCAT_WS('.', table_catalog, table_schema, table_name) AS full_table_name, *
FROM IDENTIFIER(?) -- <<DB_NAME>>.INFORMATION_SCHEMA.COLUMNS
),
snowball AS (
SELECT table_name, MAX(stats_run_date_time) AS stats_run_date_time
FROM IDENTIFIER(?) -- <<SNOWBALL_TABLE>> table
GROUP BY table_name
)
SELECT full_table_name, aprox_row_count,
CONCAT (
'INSERT INTO IDENTIFIER(''', ?, ''') ', -- SNOWBALL table
'(table_name,total_rows,table_last_altered,table_created,table_bytes,col_name,',
'col_data_type,col_hll,col_avg_length,col_null_cnt,col_min,col_max,col_top,col_mode,col_avg,stats_run_date_time)',
'SELECT ''', full_table_name, ''' AS table_name, ',
table_stats_sql,
', ARRAY_CONSTRUCT( ', col_name, ') AS col_name',
', ARRAY_CONSTRUCT( ', col_data_type, ') AS col_data_type',
', ARRAY_CONSTRUCT( ', col_hll, ') AS col_hll',
', ARRAY_CONSTRUCT( ', col_avg_length, ') AS col_avg_length',
', ARRAY_CONSTRUCT( ', col_null_cnt, ') AS col_null_cnt',
', ARRAY_CONSTRUCT( ', col_min, ') AS col_min',
', ARRAY_CONSTRUCT( ', col_max, ') AS col_max',
', ARRAY_CONSTRUCT( ', col_top, ') AS col_top',
', ARRAY_CONSTRUCT( ', col_MODE, ') AS col_MODE',
', ARRAY_CONSTRUCT( ', col_AVG, ') AS col_AVG',
', CURRENT_TIMESTAMP() AS stats_run_date_time ',
' FROM ', quoted_table_name
) AS insert_sql
FROM (
SELECT
tbl.full_table_name,
tbl.row_count AS aprox_row_count,
CONCAT ( '"', col.table_catalog, '"."', col.table_schema, '"."', col.table_name, '"' ) AS quoted_table_name,
CONCAT (
'COUNT(1) AS total_rows,''',
IFNULL( tbl.last_altered::VARCHAR, 'NULL'), ''' AS table_last_altered,''',
IFNULL( tbl.created::VARCHAR, 'NULL'), ''' AS table_created,',
IFNULL( tbl.bytes::VARCHAR, 'NULL'), ' AS table_bytes' ) AS table_stats_sql,
LISTAGG (
CONCAT ('''', col.full_table_name, '.', col.column_name, '''' ), ', '
) AS col_name,
LISTAGG ( CONCAT('''', col.data_type, '''' ), ', ' ) AS col_data_type,
LISTAGG ( CONCAT( ' HLL(', '"', col.column_name, '"',') ' ), ', ' ) AS col_hll,
LISTAGG ( CONCAT( ' AVG(ZEROIFNULL(LENGTH(', '"', col.column_name, '"','))) ' ), ', ' ) AS col_avg_length,
LISTAGG ( CONCAT( ' SUM( IFF( ', '"', col.column_name, '"',' IS NULL, 1, 0) ) ' ), ', ') AS col_null_cnt,
LISTAGG ( IFF ( col.data_type = 'NUMBER', CONCAT ( ' MODE(', '"', col.column_name, '"', ') ' ), 'NULL' ), ', ' ) AS col_MODE,
LISTAGG ( IFF ( col.data_type = 'NUMBER', CONCAT ( ' MIN(', '"', col.column_name, '"', ') ' ), 'NULL' ), ', ' ) AS col_min,
LISTAGG ( IFF ( col.data_type = 'NUMBER', CONCAT ( ' MAX(', '"', col.column_name, '"', ') ' ), 'NULL' ), ', ' ) AS col_max,
LISTAGG ( IFF ( col.data_type = 'NUMBER', CONCAT ( ' AVG(', '"', col.column_name,'"',') ' ), 'NULL' ), ', ' ) AS col_AVG,
LISTAGG ( CONCAT ( ' APPROX_TOP_K(', '"', col.column_name, '"', ', 100, 10000)' ), ', ' ) AS col_top
FROM snowball_tables tbl JOIN snowball_columns col ON col.full_table_name = tbl.full_table_name
LEFT OUTER JOIN snowball sb ON sb.table_name = tbl.full_table_name
WHERE (tbl.table_catalog, tbl.table_schema) = (?, ?)
AND ( sb.table_name IS NULL OR sb.stats_run_date_time < TIMESTAMPADD(DAY, - FLOOR(?), CURRENT_TIMESTAMP()) )
--AND tbl.row_count > 0 -- NB: also excludes views (table_type = 'VIEW')
GROUP BY tbl.full_table_name, aprox_row_count, quoted_table_name, table_stats_sql, stats_run_date_time
ORDER BY stats_run_date_time NULLS FIRST )
LIMIT ` + validLimit;
var tablesAnalysed = [];
var currentSql;
try {
currentSql = sqlGenerateInserts;
var generateInserts = snowflake.createStatement( {
sqlText: currentSql,
binds: [
`"${DB_NAME}".information_schema.tables`,
`"${DB_NAME}".information_schema.columns`,
SNOWBALL_TABLE, SNOWBALL_TABLE,
DB_NAME, SCHEMA_NAME, MAX_AGE_DAYS, LIMIT
]
} );
var insertStatements = generateInserts.execute();
// loop over generated INSERT statements and execute them
while (insertStatements.next()) {
var tableName = insertStatements.getColumnValue('FULL_TABLE_NAME');
currentSql = insertStatements.getColumnValue('INSERT_SQL');
var insertStatement = snowflake.createStatement( {
sqlText: currentSql,
binds: [ SNOWBALL_TABLE ]
} );
var insertResult = insertStatement.execute();
tablesAnalysed.push(tableName);
}
return { result: "SUCCESS", analysedTables: tablesAnalysed };
}
catch (err) {
return {
error: err,
analysedTables: tablesAnalysed,
sql: currentSql
};
}
$$;

Related

SOQL Group by IN Salesforce

String query = 'SELECT id,CreatedById,Product.Id,POCGrades__c ,fm_pocname__c,product.Name ,Visit.placeId, fm_poccode__c, createdby.LastName,Visit.LastModifiedDate, createddate, ActualBooleanValue'
+ ' FROM retailvisitkpi'
+ ' WHERE createddate = last_month and '
+ ' ( Product.Id = \'01t5j000003tszWAAQ\''
+ ' OR Product.Id = \'01t5j000003tszWAAQ\''
+ ' OR Product.Id = \'01t5j000003tt5nAAA\''
+ ' OR Product.Id = \'01t5j000003tsznAAA\''
+ ' OR Product.Id = \'01t5j000003tt1zAAA\''
+ ' OR Product.Id = \'01t5j000003tt7AAAQ\''
+ ' )';
I am having trouble to removes duplicate records based on Visit.placeID, can anybody help me out with soql
Just use hashmaps with the resulting query?
Map<String, retailvisitkpi__c> mapOfItems = new Map<String, retailvisitkpi__c>();
That will remove all the duplicates based on the Visit Place ID

Prepare WHERE Clause string for given values

I have the following details to prepare string as shown below in the expected result.
Given:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
Expected result:
(
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'') > 0
)
My attempt:
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+REPLACE(STUFF((SELECT N') '+DS3.Item+' (' + NCHAR(10) +
STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,4,N'')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,9,N''),'>','>') + N') )','&gt;','>');
PRINT(#String);
But I'm getting the following result:
( AND
ISNULL(PATINDEX(''John%'', FName), ''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'', FName), ''0'')) OR (
ISNULL(PATINDEX(''Mak'', LName), ''0'') +
ISNULL(PATINDEX(''Don'', LName), ''0'')) )
After many attempt, following does the job done.
Query:
DECLARE #VValue VARCHAR(MAX) = 'John Dee|Mak Don'
DECLARE #VColumns VARCHAR(MAX) = 'FName|LName'
DECLARE #VCondition VARCHAR(500) = 'OR'
DECLARE #VPattern VARCHAR(MAX) = 'Start|Exact'
DECLARE #VCheck VARCHAR(MAX) = '1|0'
DECLARE #String VARCHAR(MAX) = ''
SET #VCondition = '|'+#VCondition;
SET #String = REPLACE('('+STUFF((SELECT N' > 0 ) '+DS3.Item+' (' + NCHAR(10) +
REPLACE(STUFF((SELECT
CASE WHEN DS4.Item = 'Start' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Start' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +'%'''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE
''
END
+
CASE WHEN DS4.Item = 'Exact' AND DS5.Item = 0
THEN
N' + ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
WHEN DS4.Item = 'Exact' AND DS5.Item = 1
THEN
N' > 0 AND ' +NCHAR(10)+
N'ISNULL(PATINDEX('''''+DSn.Item +''''''+ N',' + DSc.Item + N'),''''0'''')'
ELSE ''
END
FROM dbo.f_split(DS1.Item,' ') DSn
CROSS APPLY dbo.f_split(DS2.Item,',') DSc
ORDER BY DSc.id, DSn.id
FOR XML PATH(N'')),1,11,N''),'>','>')
FROM dbo.udf_split (#VValue,'|') DS1
CROSS APPLY dbo.udf_split (#VColumns,'|') DS2
CROSS APPLY dbo.udf_split (#VCondition,'|') DS3
CROSS APPLY dbo.udf_split (#VPattern,'|') DS4
CROSS APPLY dbo.udf_split (#VCheck, '|') DS5
WHERE DS1.id = DS2.id AND DS2.ID = DS3.ID AND DS3.ID = DS4.ID AND DS4.ID = DS5.ID
ORDER BY DS1.id
FOR XML PATH(N'')),1,13,N''),'>','>') + N' > 0 ) ';
PRINT(#String);
Output:
(
ISNULL(PATINDEX(''John%'',FName),''0'') > 0 AND
ISNULL(PATINDEX(''Dee%'',FName),''0'') > 0
)
OR
(
ISNULL(PATINDEX(''Mak'',LName),''0'') +
ISNULL(PATINDEX(''Don'',LName),''0'') > 0
)

T-SQL function to convert numeric to words?

I am struggling to build a function that can convert a number 0-9 in a string into the spelling word of it. Here is what I have so far, and I realize 'word' is not a built in conversion, it's just what my thoughts on how to construct this would be:
CREATE FUNCTION [dbo].[fn_Numbers2Words]
(#strText VARCHAR(1000))
RETURNS varchar(1000)
AS
BEGIN
WHILE PATINDEX('%[0-9]%', #strText) > 0
BEGIN
SET #strText = STUFF(#strText, PATINDEX('%[0-9]%', #strText), 1, CONVERT(word, PATINDEX('%[0-9]%', #strText)))
END
RETURN #strText
END
The idea would be to input something like this:
SELECT [dbo].[fn_Numbers2Word]('1900testnumber')
and return this:
'oneninezerozerotestnumber'
I have tried functions that do entire numbers, but since my strings will have alphas they do not work. I also tried incorporating those functions into this function above with no luck. I'm sure it's just something I'm doing syntax wise.
Can anyone help me alter my above function so that it produces my desired result?
Since you are just wanting a simple replacement then using nested replace would super crazy fast and simple. I would avoid using a scalar function here.
declare #strText varchar(1000) = '1900testnumber'
select replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(#strText, '1', ' one'), '2', 'two'), '3', 'three'), '4', 'four'), '5', 'five'), '6', 'six'), '7', 'seven'), '8', 'eight'), '9', 'nine'), '0', 'zero')
Just for fun, here's another option that you could put into a function
Example
Declare #S varchar(max) = '1900testnumber'
Select #S = replace(#S,sFrom,sTo)
From (values ('0','zero')
,('1','one')
,('2','two')
,('3','three')
,('4','four')
,('5','five')
,('6','six')
,('7','seven')
,('8','eight')
,('9','nine')
) A(sFrom,sTo)
Select #S
Returns
oneninezerozerotestnumber
Brute force with CHOOSE:
Returns the item at the specified index from a list of values in SQL Server.
DECLARE #num INT = 20;
SELECT CHOOSE(#num,
'one ',
'two ',
'three ',
'four ',
'five ',
'six ',
'seven ',
'eight ',
'nine ',
'ten',
'eleven ',
'twelve ',
'thirteen ',
'fourteen ',
'fifteen ',
'sixteen ',
'seventeen ',
'eighteen ',
'nineteen ',
'twenty',
'twenty-one ',
'twenty-two ',
'twenty-three ',
'twenty-four ',
'twenty-five ',
'twenty-six ',
'twenty-seven ',
'twenty-eight ',
'twenty-nine ',
'thirty',
'thirty-one ',
'thirty-two ',
'thirty-three',
'thirty-four ',
'thirty-five ',
'thirty-six ',
'thirty-seven ',
'thirty-eight ',
'thirty-nine ',
'forty',
'forty-one ',
'forty-two ',
'forty-three ',
'forty-four ',
'forty-five ',
'forty-six ',
'forty-seven ',
'forty-eight ',
'forty-nine ',
'fifty',
'fifty-one ',
'fifty-two ',
'fifty-three ',
'fifty-four ',
'fifty-five ',
'fifty-six ',
'fifty-seven ',
'fifty-eight ',
'fifty-nine ',
'sixty',
'sixty-one ',
'sixty-two ',
'sixty-three ',
'sixty-four ',
'sixty-five ',
'sixty-six ',
'sixty-seven ',
'sixty-eight ',
'sixty-nine ',
'seventy',
'seventy-one ',
'seventy-two ',
'seventy-three ',
'seventy-four ',
'seventy-five ',
'seventy-six ',
'seventy-seven ',
'seventy-eight ',
'seventy-nine ',
'eighty',
'eighty-one ',
'eighty-two ',
'eighty-three ',
'eighty-four ',
'eighty-five ',
'eighty-six ',
'eighty-seven ',
'eighty-eight ',
'eighty-nine ',
'ninety',
'ninety-one ',
'ninety-two ',
'ninety-three ',
'ninety-four ',
'ninety-five ',
'ninety-six ',
'ninety-seven ',
'ninety-eight ',
'ninety-nine'
)
DBFiddle Demo

sql server query concat string with '-'

In my SQL query, I'm trying to concatenate two strings in my select clause. Here's the expected results:
col A col B Result
null null &
null '' &
null XYZ XYC
'' null &
'' '' &
'' XYZ XYC
ABC null ABC
ABC '' ABC
ABC XYZ ABC-XYC
My challenge is this - how do I get the 'dash' to show up for the last scenario and not the others?
Here's my attempt:
DECLARE #ColA as varchar(10)
DECLARE #ColB as varchar(10)
set #ColA = null; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = null; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = null; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = ''; select '&' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = ''; set #ColB = 'XYC'; select 'XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = null; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = ''; select 'ABC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
set #ColA = 'ABC';set #ColB = 'XYC'; select 'ABC-XYC' as 'Expected', COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&') as 'Actual'
Do you think I have to do one giant case when? I have many columns like this, and that would make it unbearable to read.
Thanks!
UPDATE: if I use a case when, then my select looks like this, which seems to work, but is going to be a pain.
select
case when (#ColA is not null and #ColA <> '') and
(#ColB is not null and #ColB <> '')
then #ColA + '-' + #ColB
else COALESCE(NULLIF(COALESCE(#ColA, '') + COALESCE(#ColB, ''), ''), '&')
end
really hoping someone has some suggestions for improvement!
Could you use a searched case function like this?
Select Case When isnull(ColA, '') + isnull(ColB, '') == '' Then '&'
When isnull(ColA, '') <> '' and isnull(ColB, '') <> '' Then ColA + '-' + ColB
Else isnull(ColA, '') + isnull(ColB, '')
From Table1
I think this answer isn't a whole lot different than one of the other ones, but you might try this:
SELECT
CASE
WHEN NULLIF(ColA,'') <> '' AND NULLIF(ColB,'') <> ''
THEN ColA + '-' + ColB
WHEN NULLIF(ColA,'') <> '' OR NULLIF(ColB,'') <> ''
THEN COALESCE(ColA,ColB)
ELSE '&'
END

execute result of select statement

How can I execute the results of my select query. The query below gives me some SQL statements back as result. I want to execute does statements, how to do this? All this is executed in SQL Sever Management Studio.
Query:
SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
SELECT PG.RoleNo
FROM V_PurposeGrouping PG
WHERE R.PartofFT = PG.PartofFT
AND R.RoleNo <> PG.RoleNo
)
Result:
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Teacher' WHERE RoleNo = 5.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'Teacher' WHERE RoleNo = 8.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'description' WHERE RoleNo = 10.00
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Project' WHERE RoleNo = 15.0
0
Try using your first query to open a cursor, then within the loop execute the result string as dynamic SQL.
declare commands cursor for
SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
SELECT PG.RoleNo
FROM V_PurposeGrouping PG
WHERE R.PartofFT = PG.PartofFT
AND R.RoleNo <> PG.RoleNo
)
declare #cmd varchar(max)
open commands
fetch next from commands into #cmd
while ##FETCH_STATUS=0
begin
exec(#cmd)
fetch next from commands into #cmd
end
close commands
deallocate commands
Try using this :
SELECT 'UPDATE Rolecopy SET PartofFT = ''' + R2.PlayedbyOT + ''', OriginalOT = ''' + R.PlayedbyOT + ''' WHERE RoleNo = ' + CAST(R.RoleNo AS VARCHAR) + CHAR(13)
FROM Role R INNER JOIN Role R2
ON R.PartofFT = R2.PartofFT AND R.RoleNo <> R2.RoleNo
WHERE EXISTS (
SELECT PG.RoleNo
FROM V_PurposeGrouping PG
WHERE R.PartofFT = PG.PartofFT
AND R.RoleNo <> PG.RoleNo
)
FOR XML PATH ('')
For which the result is going into one string column:
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Teacher' WHERE RoleNo = 5.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'Teacher' WHERE RoleNo = 8.00
UPDATE Rolecopy SET PartofFT = 'Project', OriginalOT = 'description' WHERE RoleNo = 10.00
UPDATE Rolecopy SET PartofFT = 'Student', OriginalOT = 'Project' WHERE RoleNo = 15.0
All in the same column.

Resources