Цитата:
Сообщение от УбийцаСмерть
Добрый вечер. Остался у кого нибудь запрос на обновление BILLING.
Нужно чтобы с tbl_rfaccount перенес аккаунты которых нету в BILLING.
А то был на форуме найти не могу. Поделитесь у кого есть.
нужен запрос на обновление базы BILLING, чтобы обновило на недостающие аккаунт из базы RF_USER таблица tbl_rfaccount, в базу BILLING таблицы tbl_user, tbl_personal_billing с проверкой если там есть аккаунт совпадение то его не дописывать снова.
|
Сделал решение на nodejs:
1. Создать папку с любым названием.
2. Создать внутри файл index.js
3. Вставить следующее содержимое и сохранить:
Код:
const sql = require('mssql');
const configRF_Billing = {
server: 'localhost',
user: 'sa',
password: 'pass',
encrypt: false
};
const configRF_User = {
server: 'localhost',
user: 'sa',
password: 'pass',
encrypt: false
};
function prepareKey(value) {
if (value === null) {
return 'null';
}
if (typeof value === 'string') {
return value;
}
let resultBytes = [];
for (let i = 0; i < value.length; i++) {
if (value[i]) {
resultBytes.push(value[i]);
}
}
if (resultBytes.length === 0) {
return '0';
}
return Buffer.from(resultBytes).toString();
}
async function getAccounts() {
try {
const poolBilling = await sql.connect(configRF_Billing);
const poolUser = await sql.connect(configRF_User);
const accountsResponse = await poolUser.request().query('SELECT [id] FROM RF_User.dbo.tbl_rfaccount');
let allAccounts = accountsResponse.recordset;
for (let account of allAccounts) {
const userId = account['UserID'] = prepareKey(account.id);
const billingUserResponse = await poolBilling.request().query('SELECT [UserID] FROM BILLING.dbo.tbl_user WHERE UserID = \'' + userId + '\'');
let billingUser = billingUserResponse.recordset;
if (!billingUser[0]) {
const billingUserInsertResponse = await poolBilling.request().query('INSERT INTO BILLING.dbo.tbl_user (UserID, Cash) VALUES (\'' + userId + '\', 0)');
if (billingUserInsertResponse.rowsAffected && billingUserInsertResponse.rowsAffected[0] > 0) {
console.log(`Успешно вставлено ${billingUserInsertResponse.rowsAffected[0]} записей`);
} else {
console.log('Ничего не было вставлено');
}
}
const billingPersBillResponse = await poolBilling.request().query('SELECT [ID] FROM BILLING.dbo.tbl_personal_billing WHERE ID = \'' + account.id + '\'');
let billingPersBill = billingPersBillResponse.recordset;
if (!billingPersBill[0]) {
const billingPersBillInsertResponse = await poolBilling.request().query('INSERT INTO BILLING.dbo.tbl_personal_billing (ID, BillingType, EndDate, RemainTime) VALUES (0x' + account.id.toString('hex') + ', 2, (CONVERT(datetime,GETDATE()+30)), 30)');
if (billingPersBillInsertResponse.rowsAffected && billingPersBillInsertResponse.rowsAffected[0] > 0) {
console.log(`Успешно вставлено ${billingPersBillInsertResponse.rowsAffected[0]} записей`);
} else {
console.log('Ничего не было вставлено');
}
}
}
// console.log(allAccounts);
await poolBilling.close();
await poolUser.close();
} catch (err) {
console.error('SQL error', err);
}
}
getAccounts();
4. В коде в configRF_Billing и в configRF_User указать логин, пароль и хост для подключения к вашей БД.
5. Для SQL запросов необходимо поправить названия баз BILLING, RF_User на те названия, какие имеют ваши данные базы.
6. Создать внутри папки файл package.json. Вставить следующее содержимое:
Код:
{
"name": "billing-accounts-sync",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node ./index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mssql": "^12.5.0"
}
}
7. Установить nodejs с официального сайта.
Запуск:
1. После выполнения пунктов выше. Перейти в папку с кодом.
2. Открыть terminal или cmd. Прописать следующую команду:
Windows (CMD):
Код:
cd "<путь до папки с файлом index.js и package.json>"
npm install
npm run start
Linux/MacOs (Terminal):
Код:
cd "<путь до папки с файлом index.js и package.json>"
npm install
npm run start
Описание:
Скрипт возьмет все записи из базы
RF_User таблицы
tbl_rfaccount и добавит данные в таблицы
tbl_user и
tbl_personal_billing базы
BILLING. Уже существующие значения затронуты не будут.
По умолчанию аккаунты в
BILLING добавляются с премиумом на 30 дней. Для таблицы
tbl_user в
BILLING новые аккаунты добавляются с CashShop равным 0.