How can I script SQL Server database diagrams? - sql-server-2008

How can I export SQL Server database diagrams as developer-friendly SQL scripts?
By developer-friendly, I mean written in a way similar to the way a human would write them as opposed to the messy many-UPDATEs style used by existing solutions.
(Note that similar questions on this site only seem to cover specific versions of SQL Server or migration of diagrams.)

Here's a script to do this. Tested in SQL Server 2008 R2 and 2012.
DECLARE #values nvarchar(max);
SET #values =
(
SELECT '
(''' + REPLACE(name, '''', '''''') + ''', ' + CAST(principal_id AS VARCHAR(100)) +', ' + CAST(version AS VARCHAR(100)) + ', ' + sys.fn_varbintohexstr(definition) + '),'
FROM sysdiagrams
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)');
SET #values = LEFT(#values, LEN(#values) - 1);
SELECT
'IF OBJECT_ID(N''dbo.sysdiagrams'') IS NULL
CREATE TABLE dbo.sysdiagrams
(
name sysname NOT NULL,
principal_id int NOT NULL,
diagram_id int PRIMARY KEY IDENTITY,
version int,
definition varbinary(max)
CONSTRAINT UK_principal_name UNIQUE
(
principal_id,
name
)
);
MERGE sysdiagrams AS Target
USING
(
VALUES' + #values + '
) AS Source (name, principal_id, version, definition)
ON Target.name = Source.name
AND Target.principal_id = Source.principal_id
WHEN MATCHED THEN
UPDATE SET version = Source.version, definition = Source.definition
WHEN NOT MATCHED BY Target THEN
INSERT (name, principal_id, version, definition)
VALUES (name, principal_id, version, definition);
';
It basically exports the contents of the sysdiagrams table. Note that it does not retain the diagrams' id numbers. It also retains who created the diagrams, but the id number should also exist in the target database.
If you run the resultant script on a server instance that doesn't have the database diagramming objects, it should still work. However, after doing this, in order for them to appear in SSMS, I think you'll need to expand the Database Diagrams node and click Yes when asked to create them.
This is based on the 2008 script from here.
Note that there is a catch! SSMS and other Microsoft tools truncate the resulting text in the result set if you have more than a few diagrams. To get the full text, here's a PowerShell script to run the query and put the output in the clipboard:
$ErrorActionPreference = "Stop"
function Pause([string]$message) {
Write-Host $message
$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | Out-Null
}
function Set-Clipboard {
$input | PowerShell -NoProfile -STA -Command {
Add-Type -AssemblyName "System.Windows.Forms"
[Windows.Forms.Clipboard]::SetText($input)
}
}
$connection = New-Object System.Data.SqlClient.SqlConnection ("Data Source=DATABASE_INSTANCE;Initial Catalog=DATABASE;Integrated Security=SSPI")
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = #"
--SQL CODE
"#
$command.CommandTimeout = 60
$result = $command.ExecuteScalar()
$command.Dispose()
$connection.Dispose()
Pause "Press any key to copy the resulting SQL to the clipboard..."
$result | Set-Clipboard
Fill in the database, instance name, and SQL placeholders.

#Sam's answer is 100% correct and works (against 2019, too), and you still must do as he says: executing using Powershell
His original PS script features a Pause near the end, and that bugs-out for me when I run the script in Powershell ISE (probably due to my own naivete)
So, here's my slightly changed PS script (with the SQL embedded already) that is a near direct steal of #Sam's lovely work
$ErrorActionPreference = "Stop"
function Set-Clipboard {
$input | PowerShell -NoProfile -STA -Command {
Add-Type -AssemblyName "System.Windows.Forms"
[Windows.Forms.Clipboard]::SetText($input)
}
}
$connection = New-Object System.Data.SqlClient.SqlConnection ("Data Source=localhost;Initial Catalog=MySpecialDataBase;Integrated Security=SSPI")
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = #"
DECLARE #values nvarchar(max);
SET #values =
(
SELECT '
(''' + REPLACE(name, '''', '''''') + ''', ' + CAST(principal_id AS VARCHAR(100)) +', ' + CAST(version AS VARCHAR(100)) + ', ' + sys.fn_varbintohexstr(definition) + '),'
FROM sysdiagrams
FOR XML PATH(''), TYPE
).value('.', 'nvarchar(max)');
SET #values = LEFT(#values, LEN(#values) - 1);
SELECT
'IF OBJECT_ID(N''dbo.sysdiagrams'') IS NULL
CREATE TABLE dbo.sysdiagrams
(
name sysname NOT NULL,
principal_id int NOT NULL,
diagram_id int PRIMARY KEY IDENTITY,
version int,
definition varbinary(max)
CONSTRAINT UK_principal_name UNIQUE
(
principal_id,
name
)
);
MERGE sysdiagrams AS Target
USING
(
VALUES' + #values + '
) AS Source (name, principal_id, version, definition)
ON Target.name = Source.name
AND Target.principal_id = Source.principal_id
WHEN MATCHED THEN
UPDATE SET version = Source.version, definition = Source.definition
WHEN NOT MATCHED BY Target THEN
INSERT (name, principal_id, version, definition)
VALUES (name, principal_id, version, definition);
';
"#
$command.CommandTimeout = 60
$result = $command.ExecuteScalar()
$command.Dispose()
$connection.Dispose()
$result | Set-Clipboard
echo "Your SQL Diagram was successfully scripted out and copied to the clipbaord"
Just launch your Windows PowerShell ISE, paste this into the top pane, update the connection string ~ line 10. Save the script. Run the script.

Related

Executing SQL with parameters in SSIS

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.

How to dump an entire SQL Server 2014 database into a file, to be imported into a Postgres database?

I have a SQL Server 2014 database from which I need to dump just the table data (no indexes, stored procedures, or anything else).
This dump needs to be imported into a Postgres 9.3 database "as-is".
What id the proper command line to create such a dump?
I must admit, this is more sort of a joke... You should rather follow the hint to use "Export" and write this to some kind of CSV. Just for fun:
EDIT: create a column list to avoid binary columns...
columns, which are not directly convertible into XML RAW are added with "invalid data":
DECLARE #Commands TABLE(ID INT IDENTITY,cmd NVARCHAR(MAX));
INSERT INTO #Commands(cmd)
SELECT '(SELECT TOP 3 '
+ STUFF(
(
SELECT ',' + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE c.TABLE_CATALOG=t.TABLE_CATALOG AND c.TABLE_SCHEMA=t.TABLE_SCHEMA AND c.TABLE_NAME=t.TABLE_NAME
AND c.DATA_TYPE NOT IN('image','text') AND c.DATA_TYPE NOT LIKE '%BINARY%'
FOR XML PATH('')
),1,1,''
)
+
(
SELECT ',''invalid data'' AS ' + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS AS c
WHERE c.TABLE_CATALOG=t.TABLE_CATALOG AND c.TABLE_SCHEMA=t.TABLE_SCHEMA AND c.TABLE_NAME=t.TABLE_NAME
AND (c.DATA_TYPE IN('image','text') OR c.DATA_TYPE LIKE '%BINARY%')
FOR XML PATH('')
)
+ ' FROM ' + QUOTENAME(t.TABLE_CATALOG) + '.' + QUOTENAME(t.TABLE_SCHEMA) + '.'
+ QUOTENAME(t.TABLE_NAME) + ' FOR XML RAW,TYPE) AS ' + QUOTENAME(t.TABLE_CATALOG + '_' + t.TABLE_SCHEMA + '_' + t.TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES AS t WHERE t.TABLE_TYPE='BASE TABLE';
DECLARE #finalCommand NVARCHAR(MAX)=
(
SELECT 'SELECT '
+'(SELECT TABLE_CATALOG,TABLE_SCHEMA,TABLE_NAME FROM INFORMATION_SCHEMA.TABLES FOR XML RAW,TYPE) AS ListOfTables'
+ (
SELECT ',' + cmd
FROM #Commands
ORDER BY ID
FOR XML PATH('')
)
+ ' FOR XML PATH(''AllTables'')'
);
EXEC( #finalCommand);
Microsoft recently announced a new command line tool mssql-scripter (it's open source and multi-OS) that allows you to generate T-SQL scripts for databases/database objects as a .sql file. The announcement is here.
Once launching the scripter you'll want to run a command similar to the following:
$ mssql-scripter -S serverName -U userName -d databaseName --data-only
More details are on the GitHub page usage guide: https://github.com/Microsoft/sql-xplat-cli/blob/dev/doc/usage_guide.md

BCP SQL exporting to CSV

Im trying to run a Store procedure query to export to CSV file using bcp as a daily task on SQL server
using a normal query works fine for example
select #csv = 'bcp "select * from Table" queryout '+#FileAndPath2+' -c -t, -T -S' +##servername
However when I add my query which is a list of transactions data within a date range it seems to crash
#p_companyId uniqueidentifier = '189be460-99d1-42e9-b4ed-8de6f8724ce8',
#p_Path varchar(300) = 'C:\temp\','
#p_Date datetime = getutcdate
set #FileAndPath2=#p_Path + CONVERT(nvarchar(30), #p_Date, 112) + '_' + CONVERT(varchar(36), #p_companyId) + '_transactionslog.csv';
declare #csv varchar(8000)
declare #csvSQL varchar(8000)
set #csvSQL = 'SELECT TOP (100) [KICSDEV].dbo.MOVIEDETAIL.Title , [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MemberId, [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime as ''DateTime'' FROM [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG INNER JOIN [KICSDEV].dbo.MOVIEDETAIL ON [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MovieDetailId = [KICSDEV].dbo.MOVIEDETAIL.MovieDetailId INNER JOIN [KICSDEV].dbo.MEMBER ON [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MemberId = [KICSDEV].dbo.MEMBER.MemberId INNER JOIN [KICSDEV].dbo.CINEMA ON [KICSDEV].dbo.MEMBER.CinemaId = [KICSDEV].dbo.CINEMA.CinemaId WHERE ([KICSDEV].dbo.CINEMA.CompanyId = '+ #p_companyId + ' and [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime >= ' + #p_Date +' and [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime < DATEADD (day , 1 , '+#p_Date+'))'
select #csvSQL
select #csv = 'bcp "'+ #csvSQL +'" queryout '+#FileAndPath2+' -c -t, -T -S' +##servername
exec master..xp_cmdshell #csv
When I run it comes up as "The data types varchar and uniqueidentifier are incompatible in the add operator." error
When i change the Company to the string instead of the variable in the query it works fine but errors on this.
set #csvSQL = 'SELECT TOP (100) [KICSDEV].dbo.MOVIEDETAIL.Title , [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MemberId, [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime as ''DateTime'' FROM [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG INNER JOIN [KICSDEV].dbo.MOVIEDETAIL ON [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MovieDetailId = [KICSDEV].dbo.MOVIEDETAIL.MovieDetailId INNER JOIN [KICSDEV].dbo.MEMBER ON [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.MemberId = [KICSDEV].dbo.MEMBER.MemberId INNER JOIN [KICSDEV].dbo.CINEMA ON [KICSDEV].dbo.MEMBER.CinemaId = [KICSDEV].dbo.CINEMA.CinemaId WHERE ([KICSDEV].dbo.CINEMA.CompanyId = ''189be460-99d1-42e9-b4ed-8de6f8724ce8'' and [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime >= ' + #p_Date +' and [KICSDEV].dbo.MEMBERMOVIEPURCHASELOG.CreateDateTime < DATEADD (day , 1 , '+#p_Date+'))'
Conversion failed when converting date and/or time from character string.
I think it something to do with all the delimiters and data types.
Several problems here. Think of the problem this way. You are building a command line parameter for a command line utility, so everything has to be built into a string.
Step 1: Make sure everything is a string before concatenating the query
You are missing some casts Cast(#p_companyId as VarChar(36)) and CAST( #p_Date as VarChar(25)) you also need to quote the cast of the company id and dates in the formatted string. I recommend making a new variable to have the UTC date as a string #p_DateAsStr varchar(25) = CAST( #p_Date as VarChar(25) ), instead of repeating that over and over.
Step 2: String values in the query need to be quoted
Since you are calling BCP you have to format the query as a string, string parameters need to be quoted. You have to use the single quotes because the string to BCP is in double quotes, for instance:
set #csvSQL = 'SELECT .... WHERE CompanyId = '''+ Cast(#p_companyId as VarChar(36)) + ''....'
Step 3: Convert any strings in the query back to native types as needed by built in functions
We are OK with the GUID specified as a string (if we quote it), but for DataAdd we need to convert back from string to date Like this
CreateDateTime < DATEADD (day , 1 , CAST(''' +#p_DateAsStr+''' as DateTime))
[Update] added a quoted string for the date

Extracting Number From String SQL

I have a normal SQL statement:
SELECT VALUE_ID, UF_CRM_TASK FROM b_uts_tasks_task
Now this returns a a different field everytime but they take the form of the following:
a:1:{i:0;s:7:"CO_2012";} or a:1:{i:0;s:5:"CO_12";} or a:1:{i:0;s:7:"CO_2017";}
Basically they're different everytime. What I need is to just get the number after the CO_ part. I have tried TRIM but because everything changes in the leading and trailing section I don't think this would work.
I have looked on Stack Overflow for a while and cannot find it. I know how to do it in PHP:
$data = $row['UF_CRM_TASK'];
$companyID = substr($data, strpos($data, "CO_") + 1);
$newCompanyID = preg_replace('/[^0-9.]+/', '', $companyID);
But not SQL. Thanks in advance
In MYSQL is a bit ugly:
/*SUBSTRING_INDEX BASED ON CO_ AND THE LAST " - in 2 SUBSTRINGS*/
SELECT `VALUE_ID`, SUBSTRING_INDEX(SUBSTRING_INDEX(`UF_CRM_TASK`, 'CO_', -1), '"', 1) AS `COMPANY_ID` FROM `b_uts_tasks_task`
In PHP you can just unserialize():
$data = unserialize($row['UF_CRM_TASK']);
$companyID = str_replace('CO_', '', $data[0]);
eg:
$data = unserialize('a:1:{i:0;s:5:"CO_12";}');
echo str_replace('CO_', '', $data[0]);
//==> 12
You need to use CharIndex and SubString (Microsoft SQL) or
This is the sample code I made for my Microsoft SQL server:
declare #companyIdString varchar(50) = 'a:1:{i:0;s:7:"CO_2012";}'
print 'Company ID in a string: ' + #companyIdString
print 'Find first position: ' + Cast(charindex('"CO_', #companyIdString) as varchar(2))
print 'Locate the second position (the last "): ' + Cast(charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) as varchar(2))
print 'Extracted Company Id: ' + substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4)
select
#companyIdString as CompanyIdString,
substring(#companyIdString,charindex('"CO_', #companyIdString)+4, charindex('"', #companyIdString, charindex('"CO_', #companyIdString)+4) - charindex('"CO_', #companyIdString) - 4) as CompanyId
I also made the same code on a mySQL server:
set #companyIdString := 'a:1:{i:0;s:7:"CO_2012";}';
select
#companyIdString as CompanyIdString,
substring_index(substring_index(substring_index(#companyIdString, '"', 2), '"', -1), '_', -1) as CompanyId
The substring_index starts by locating the second " (string is now a:1:{i:0;s:7:"CO_2012), then it searches backward with the -1 to locate the first " (string is now CO_2012). And then it searches backward for the underscore (string is now 2012).

How to run two queries?(Joomla, mysql)

I want that when someone votes for article information, it gets inserted into two tables
(or run any two queries, does not matter, insert, update or select).
I am using Joomla! 2.5.0 Stable.
components/com_content/models/article.php
public function storeVote($pk = 0, $rate = 0)
when executing this query:
$db->setQuery(
'INSERT INTO #__content_rating ( content_id, lastip, rating_sum, rating_count )' .
' VALUES ( '.(int) $pk.', '.$db->Quote($userIP).', '.(int) $rate.', 1 )'
I want that the information in #__content table will be inserted too.
How do I achieve that?
I tried following, but it does not work:
$db->setQuery(
'INSERT INTO #__content_rating ( content_id, lastip, rating_sum, rating_count )' .
' VALUES ( '.(int) $pk.', '.$db->Quote($userIP).', '.(int) $rate.', 1 )'
// 'UPDATE #__content ' .
' SET testas2 = rating_sum + '.(int) $rate .
' WHERE content_id = '.(int) $pk
// 'INSERT INTO #__content ( testas2 )' .
' VALUES (7799)'
);
This is picture with the syntax:
http://i49.tinypic.com/1ruux0.jpg
I read about MySQL transaction, will it help me in this case? If yes, then what should the syntax should look like?
Any advice is much appreciated.
Try to run the following directly in the DB (use phpAdmin):
UPDATE edqfi_content_rating , edqfi_content
SET edqfi_content_rating.rating_count = edqfi_content_rating.rating_count + 1,
edqfi_content_rating.rating_sum = edqfi_content_rating.rating_sum + 3,
edqfi_content_rating.lastip = '88.119.189.154',
edqfi_content.testas2=edqfi_content_rating.rating_sum + 3
WHERE edqfi_content_rating.content_id = 13
AND edqfi_content.id= 13
and see if you get any errors.