DECLARE #sql nvarchar(4000)
SET #sql='SELECT DISTINCT
WS.SIMNumber,
SMTP.SMTPMappingId,
CONVERT(VARCHAR(11),WS.ExpiryDate,106) as ExpiryDate,
CASE
WHEN BES.DisplayName IS NOT NULL THEN BES.DisplayName+'#'+SMTP.DomainName
ELSE
CASE WHEN BES.PIN IS NOT NULL THEN BES.PIN+'#'+SMTP.DomainName
ELSE '' END END AS EmailId,
CASE
WHEN (SELECT COUNT(*) FROM dbo.ExpiringEmailSimCardSent WHERE SimNumber=WS.SIMNumber AND ExpiryDate=WS.ExpiryDate)>0
THEN CONVERT(BIT,1)
ELSE CONVERT(BIT,0)
END AS IsEMailSent
FROM
WEBSERVICE_CACHE AS WS
LEFT OUTER JOIN
BES_SERVER_CACHE AS BES ON WS.SIMNumber = LEFT(BES.ICCID,19)
LEFT OUTER JOIN
BES_SMTP_Mapping AS SMTP ON BES.BESSqlServer = SMTP.BesServer
WHERE
CONVERT(DATETIME, GETDATE(), 109) > CONVERT(DATETIME, WS.ExpiryDate, 109)'
EXECUTE sp_executesql #sql
I have this SQL query want to convert it into a `nvarchar` variable because of # and '' . I am getting some errors
I am getting this errorMsg 102, Level 15, State 1, Line 9
Incorrect syntax near '#'.
If I rectify that it comes for another at # and ' '
You have to 'escape' your quotes:
This:
BES.PIN+'#'+SMTP.DomainName
Should be something like this:
BES.PIN+'''#'''+SMTP.DomainNam
experiment....
Related
So I'm trying to rewrite a MySQL query to MSSQL, but it's not as easy as I thought, since the functions from MySQL are not used in MSSQL(2014).
My MySQL query looks like this:
SELECT
(SELECT
REPLACE(GROUP_CONCAT(DISTINCT CONCAT(versions.Name, ': ', versions.Version)),
',',
', </br>') AS VersionString
FROM
target
LEFT JOIN
versions ON versions.targetid = target.id
WHERE
target.TestJobId = testruns.TestJobId
AND versions.Name = 'SW') AS NameVersion
FROM
testruns
I've tried to rewrite it, but I can't seem to make it work.
SELECT
(SELECT stuff(
(SELECT DISTINCT ', <br>' + cast([testreportingdebug].versions.Name + ': ' + [testreportingdebug].versions.Version AS VARCHAR(max))
FROM [SwMetrics].[testreportingdebug].[target]
FOR XML path('')
), 1, 1, '') AS VersionString
FROM
[testreportingdebug].[target]
LEFT JOIN
[testreportingdebug].[versions] ON [testreportingdebug].[versions].[targetid] = [testreportingdebug].[target].[id]
WHERE
[testreportingdebug].[target].[TestJobId] = [testreportingdebug].[testruns].[TestJobId]
AND [testreportingdebug].[versions].[Name] = 'SW') AS NameVersion
FROM
[testreportingdebug].[testruns];
The error I get is:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
I'm a bit stuck what/how to rewrite this query. How can I rewrite it to work in SQL Server?
In SQL server STRING_AGG() replaces GROUP_CONCAT() and we can specify the seperator as </br>.
SELECT
STRING_AGG(
DISTINCT CONCAT(
versions.Name,
': ',
versions.Version,
'</br') AS VersionString
FROM target
LEFT JOIN versions
ON versions.targetid = target.id
AND target.TestJobId = testruns.TestJobId
WHERE versions.Name = 'SW';
I have the following data,
{"value": 0, "action": "UPDATED", "effectiveFrom": "2019-01-31T07:27:13.000Z"}
I am trying to extract the time value using the below SQL,
SELECT CASE
WHEN JSON_EXTRACT(changeData, '$.action') = 'UPDATED' THEN
time(replace(JSON_EXTRACT(changeData, '$.effectiveFrom'), 'T', ' '))
ELSE
'N'
END AS ACTION
FROM change
I used the replace function having read here that for mysql the 'T' should be replaced.
My sql is returning null.
You also need to replace double-quote and Z characters with '' or ' ' while replacing T with ' ' character for the time literal as
SELECT JSON_EXTRACT(changeData, '$.value') AS value,
CASE
WHEN JSON_EXTRACT(changeData, '$.action') = 'UPDATED'
THEN
TIME(
REPLACE(REPLACE(REPLACE(
JSON_EXTRACT(changeData, '$.effectiveFrom')
,'"',''),"Z",''),"T",' ')
)
ELSE 'N'
END AS action
FROM `change`
Demo
How do I execute the SQL script below a SSIS project? I've tried setting up parameters & variables; however.... nothing I do seems to pass the parameters via SSIS
declare #businessunit varchar(255) = 'Test'
declare #advisor varchar(255) = 'Smith'
declare #iuid int =
(
select U.[iuid]
from U
inner join [dbo].A on u.[ipartyid] = A.[iuserid]
inner join [dbo].B on A.[ibusinessunitid] = B.[ipartyid]
inner join [dbo].C on u.[ipartyid] = C.[ipartyid]
inner join [dbo].D on C.[ipartyid] = D.[ipartyid]
where 1 = 1
and B.[name] = #businessunit
and D.[lastname] = #advisor
)
select HHName
,HHID = h.ihhid
,FNAME =
case
when charindex(',', h.vhhname) > 0 and trim(substring(h.vhhname, patindex('% i%', h.vhhname), len(h.vhhname))) in ('i', 'ii', 'iii')
then concat(dbo.Propercase(concat(trim(substring(trim(substring(h.vhhname, charindex(' ', h.vhhname), len(h.vhhname))), 1, charindex(' ', trim(substring(h.vhhname, charindex(' ', h.vhhname), len(h.vhhname)))))), ' ', trim(substring(h.vhhname, 1, (charindex(',', h.vhhname) - 1))))), UPPER(substring(h.vhhname, patindex('% i%', h.vhhname), len(h.vhhname))))
when charindex(',', h.vhhname) > 0 and nullif(h.vdescr, '') is null
then dbo.Propercase(replace(replace(concat(trim(substring(h.vhhname, (charindex(',', h.vhhname) + 1), len(h.vhhname))), ' ', trim(substring(h.vhhname, 1, (charindex(',', h.vhhname) - 1)))), '+', '&'), ' and ', ' & '))
else dbo.Propercase(replace(isnull(nullif(h.vdescr, ''), h.vhhname), ' and ', ' & '))
end
,RepNo = h.planid
from [dbo].[HH] h
inner join
(
select u.[usertype]
,a.[user_planid]
from [dbo].users u
inner join [dbo].user_access a on u.iuid = a.iuid
where 1 = 1
and u.[usertype] <> 'e'
and u.iuid = #iuid
group by u.[usertype],a.[user_planid]
) p
on h.[planid] = p.[user_planid]
I'm going to assume you already have two SSIS variables that correspond to #businessunit and #advisor and they are being populated with the correct values already.
You can use an Execute SQL Task with parameter mapping to run your query. First thing you want to do is open the task editor, and configure your db connection. Next, hit the three dots next to SQLStatement to pull up the query editor window. Now you can start transposing your query, with a few modifications. I find that the Execute SQL Task works best when you separate variable declaration and assignment statements. You can use the following as your query text:
declare #businessunit varchar(255)
declare #advisor varchar(255)
declare #iuid int
SET #businessunit = ?
SET #advisor = ?
SET #iuid =
(
select U.[iuid]
from U
inner join [dbo].A on u.[ipartyid] = A.[iuserid]
inner join [dbo].B on A.[ibusinessunitid] = B.[ipartyid]
inner join [dbo].C on u.[ipartyid] = C.[ipartyid]
inner join [dbo].D on C.[ipartyid] = D.[ipartyid]
where 1 = 1
and B.[name] = #businessunit
and D.[lastname] = #advisor
)
select HHName
,HHID = h.ihhid
,FNAME =
case
when charindex(',', h.vhhname) > 0 and trim(substring(h.vhhname, patindex('% i%', h.vhhname), len(h.vhhname))) in ('i', 'ii', 'iii')
then concat(dbo.Propercase(concat(trim(substring(trim(substring(h.vhhname, charindex(' ', h.vhhname), len(h.vhhname))), 1, charindex(' ', trim(substring(h.vhhname, charindex(' ', h.vhhname), len(h.vhhname)))))), ' ', trim(substring(h.vhhname, 1, (charindex(',', h.vhhname) - 1))))), UPPER(substring(h.vhhname, patindex('% i%', h.vhhname), len(h.vhhname))))
when charindex(',', h.vhhname) > 0 and nullif(h.vdescr, '') is null
then dbo.Propercase(replace(replace(concat(trim(substring(h.vhhname, (charindex(',', h.vhhname) + 1), len(h.vhhname))), ' ', trim(substring(h.vhhname, 1, (charindex(',', h.vhhname) - 1)))), '+', '&'), ' and ', ' & '))
else dbo.Propercase(replace(isnull(nullif(h.vdescr, ''), h.vhhname), ' and ', ' & '))
end
,RepNo = h.planid
from [dbo].[HH] h
inner join
(
select u.[usertype]
,a.[user_planid]
from [dbo].users u
inner join [dbo].user_access a on u.iuid = a.iuid
where 1 = 1
and u.[usertype] <> 'e'
and u.iuid = #iuid
group by u.[usertype],a.[user_planid]
) p
on h.[planid] = p.[user_planid]
Hit OK in the query editor window.
The ? in the SET statements tell the task to pull the values from the Parameter Mapping. So now let's configure the parameter mappings.
In the left pane of the Execute SQL Task Editor, click on Parameter Mapping. If your db connection is OLE or EXCEL, then the Parameter Name will start with 0 and increment by one for each additional parameter. If it's an ODBC connection, you'll start with 1 instead. The parameter names match up with the ordinal position of the ?. So in our example here, #businessunit would be the first parameter mapped and #advisor would be the second. Now you're going to add two parameters. Hit the Add button, then change the Variable Name to your first SSIS variable. Leave Direction set to Input, change Data Type to VARCHAR, set the Parameter Name, then set the Parameter Size to 255. Repeat for the second variable. Your paramter mappings should look something like this:
Make sure you hit OK to save all your changes.
For a script as long as this, one solution that may work for you depending on what you are trying to achieve is to use SSIS script tasks.
Script tasks allow you to use C# (Or Visual Basic) in order to execute SQL via the same System.Data.SqlClient class that you would normally use in other C# programs, such as a console or ASP.NET application.
For your SQL above, put it into a stored procedure, and then execute this stored procedure within the script task. You could then use SqlDataReader or SqlDataAdapter to then read and store the result into a model.
From there, you can choose to manipulate the data within the SSIS script task.
For Example:
SqlConnection connection = new Connection("connection string");
using(SqlCommand command = new SqlCommand("Trans-SQL or stored procedure name", connection)
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(/*Add your parameters...*/);
connection.Open()
SqlDataReader reader = command.ExecuteReader()
while (reader.Read())
{
//Use reader["name"] in here to read values from response into a model
}
}
Is a completely valid way of querying data within a SSIS task. If you would rather not deal with a Reader, you can use the SqlDataAdapter and use the Fill() method to store the result(s) in a dataset.
Overall, when dealing with complex data (and where efficiency isn't too much of a concern), I find that completing actions within SSIS script tasks that get triggered by the control logic is the easier way to use SSIS.
You may find this Integration Services Programming Overview documentation site useful as a reference for some of the things you can do with SSIS script tasks.
On a final note, please be aware that script tasks in SSIS do have some limitations, a key one is that there is generally worse support for newer C# features, that cause issues such as not being able to hit debug breakpoints.
I am trying to export all the user information / permissions to a file for documentation. I trying to find a script out this task, is there anyway to pull all the permission from all the SQL databases from a server at one time? Working with SQL 2008 and 2012.
#Damaged I used powershell to export "Database-Level Object Permissions".. you can try below soluition.
[string]$SrvIns = 'YourServerName'
[string]$db = 'YourDatabaseName'
$sql = " SELECT
usr.name AS 'User',
CASE WHEN perm.state <> 'W' THEN perm.state_desc ELSE 'GRANT' END AS PermType,
perm.permission_name,
USER_NAME(obj.schema_id) AS SchemaName,
obj.name AS ObjectName,
CASE obj.Type
WHEN 'U' THEN 'Table'
WHEN 'V' THEN 'View'
WHEN 'P' THEN 'Stored Proc'
WHEN 'FN' THEN 'Function'
ELSE obj.Type END AS ObjectType,
CASE WHEN cl.column_id IS NULL THEN '--' ELSE cl.name END AS ColumnName,
CASE WHEN perm.state = 'W' THEN 'X' ELSE '--' END AS IsGrantOption
FROM
sys.database_permissions AS perm
INNER JOIN sys.objects AS obj
ON perm.major_id = obj.[object_id]
INNER JOIN sys.database_principals AS usr
ON perm.grantee_principal_id = usr.principal_id
LEFT JOIN sys.columns AS cl
ON cl.column_id = perm.minor_id AND cl.[object_id] = perm.major_id
WHERE
obj.Type <> 'S'
ORDER BY
usr.name, perm.state_desc ASC, perm.permission_name ASC"
Invoke-Sqlcmd -ServerInstance $SrvIns -Database $db -Query $sql | Export-Csv C:\permission.csv
Good Luck**
Here is a script that someone found for me it works perfect. I'm posting so other people can use.
set nocount on
declare #permission table (
Database_Name sysname,
User_Role_Name sysname,
Account_Type nvarchar(60),
Action_Type nvarchar(128),
Permission nvarchar(60),
ObjectName sysname null,
Object_Type nvarchar(60)
)
declare #dbs table (dbname sysname)
declare #Next sysname
insert into #dbs
select name from sys.databases order by name
select top 1 #Next = dbname from #dbs
while (##rowcount<>0)
begin
insert into #permission
exec('use [' + #Next + ']
declare #objects table (obj_id int, obj_type char(2))
insert into #objects
select id, xtype from master.sys.sysobjects
insert into #objects
select object_id, type from sys.objects
SELECT ''' + #Next + ''', a.name as ''User or Role Name'', a.type_desc as ''Account Type'',
d.permission_name as ''Type of Permission'', d.state_desc as ''State of Permission'',
OBJECT_SCHEMA_NAME(d.major_id) + ''.'' + object_name(d.major_id) as ''Object Name'',
case e.obj_type
when ''AF'' then ''Aggregate function (CLR)''
when ''C'' then ''CHECK constraint''
when ''D'' then ''DEFAULT (constraint or stand-alone)''
when ''F'' then ''FOREIGN KEY constraint''
when ''PK'' then ''PRIMARY KEY constraint''
when ''P'' then ''SQL stored procedure''
when ''PC'' then ''Assembly (CLR) stored procedure''
when ''FN'' then ''SQL scalar function''
when ''FS'' then ''Assembly (CLR) scalar function''
when ''FT'' then ''Assembly (CLR) table-valued function''
when ''R'' then ''Rule (old-style, stand-alone)''
when ''RF'' then ''Replication-filter-procedure''
when ''S'' then ''System base table''
when ''SN'' then ''Synonym''
when ''SQ'' then ''Service queue''
when ''TA'' then ''Assembly (CLR) DML trigger''
when ''TR'' then ''SQL DML trigger''
when ''IF'' then ''SQL inline table-valued function''
when ''TF'' then ''SQL table-valued-function''
when ''U'' then ''Table (user-defined)''
when ''UQ'' then ''UNIQUE constraint''
when ''V'' then ''View''
when ''X'' then ''Extended stored procedure''
when ''IT'' then ''Internal table''
end as ''Object Type''
FROM [' + #Next + '].sys.database_principals a
left join [' + #Next + '].sys.database_permissions d on a.principal_id = d.grantee_principal_id
left join #objects e on d.major_id = e.obj_id
order by a.name, d.class_desc')
delete #dbs where dbname = #Next
select top 1 #Next = dbname from #dbs
end
set nocount off
select ##SERVERNAME as Server_name,* from #permission
I have a query that I am trying to convert to MySQL from MS SQL Server 2008. It runs fine on MSSQL,
I get the error
"Incorrect parameter count in the call to native function 'ISNULL'".
How do I solve this?
SELECT DISTINCT
dbo.`#EIM_PROCESS_DATA`.U_Tax_year,
dbo.`#EIM_PROCESS_DATA`.U_Employee_ID,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS033' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS PAYE,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS014' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS TOTALTAXABLE,
dbo.OADM.CompnyName,
dbo.OADM.CompnyAddr,
dbo.OADM.TaxIdNum,
dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '') + '' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName
FROM
dbo.`#EIM_PROCESS_DATA`
INNER JOIN
dbo.OHEM ON dbo.`#EIM_PROCESS_DATA`.U_Employee_ID = dbo.OHEM.empID
CROSS JOIN
dbo.OADM
GROUP BY dbo.`#EIM_PROCESS_DATA`.U_Tax_year , dbo.`#EIM_PROCESS_DATA`.U_Employee_ID , dbo.OADM.CompnyName , dbo.OADM.CompnyAddr , dbo.OADM.TaxIdNum , dbo.OHEM.lastName , dbo.OHEM.firstName , dbo.OHEM.middleName , dbo.`#EIM_PROCESS_DATA`.U_PD_code
MySQL
SELECT DISTINCT
processdata.taxYear, processdata.empID,
CASE WHEN processdata.edCode = 'SYS033' THEN SUM (processdata.amount) END AS PAYE,
CASE WHEN processdata.edCode = 'SYS014' THEN SUM (processdata.amount) END AS TOTALTAXABLE,
company.companyName, company.streetAddress, company.companyPIN, employeemaster.lastName + ', ' + IFNULL(employeemaster.middleName, '')
+ ' ' + IFNULL(employeemaster.firstName, '') AS EmployeeName
FROM
processdata INNER JOIN
employeemaster ON processdata.empID = employeemaster.empID
CROSS JOIN company
GROUP BY processdata.taxYear, processdata.empID, company.companyName, company.streetAddress, company.companyPIN,
employeemaster.lastName, employeemaster.firstName, employeemaster.middleName, processdata.edCode
The MySQL equivalent of ISNULL is IFNULL
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns
expr2.
Maybe also look at SQL NULL Functions
The ISNULL from MySQL is used to check if a value is null
If expr is NULL, ISNULL() returns 1, otherwise it returns 0.
I would suggest that you switch to the ANSI standard function coalesce():
(dbo.OHEM.lastName + ', ' + coalesce(dbo.OHEM.middleName, '') + '' + coalesce(dbo.OHEM.firstName, '')
) AS EmployeeName
You could also make your query easier to read by including table aliases.
EDIT:
As a note, I seemed to have missed the direction of conversion. The MySQL query would use concat():
CONCAT(OHEM.lastName, ', ', coalesce(OHEM.middleName, ''),
coalesce(concat(' ', OHEM.firstName), '')
) AS EmployeeName
I was getting an error when running JUnit tests against a query which had ISNULL(value) with the error saying ISNULL needed two parameters. I fixed this by changing the query to have value is null and the code works the same while the tests now work.