S
S
stainer2022-02-11 13:56:55
Transact SQL
stainer, 2022-02-11 13:56:55

What's wrong with a T-SQL query?

Good afternoon, I can not understand what is the request error.
Request:

SELECT * INTO #temp_MarkaAutos_1644569816 FROM MarkaAutos WHERE 1<>1; --создаем временную таблицу из существующей (структура)

SET IDENTITY_INSERT #temp_MarkaAutos_1644569816 ON; --разрешаем вставку рк временной
SET IDENTITY_INSERT MarkaAutos ON; --разрешаем вставку рк

INSERT INTO #temp_MarkaAutos_1644569816 (id,name,icon,slug,rusName) VALUES ('1','Acura','.jpg','acura','Акура');

MERGE INTO MarkaAutos AS t 
USING #temp_MarkaAutos_1644569816 AS t2 
ON 1=2 
WHEN MATCHED THEN 
  UPDATE SET name = t2.name,icon = t2.icon,slug = t2.slug,rusName = t2.rusName 
WHEN NOT MATCHED THEN 
  INSERT (id,name,icon,slug,rusName) VALUES (t2.id,t2.name,t2.icon,t2.slug,t2.rusName);

SET IDENTITY_INSERT MarkaAutos OFF; --отключаем вставку рк

DROP TABLE #temp_MarkaAutos_1644569816; --удаляем временную таблицу


Mistake:

SQL (8107): IDENTITY_INSERT is already ON for table 'tempdb.dbo.#temp_MarkaAutos_1644569816'. Cannot perform SET operation for table 'MarkaAutos'.uery


At the same time, if I remove the permission to insert the RC into the temporary table from the query, then the error is that it is impossible to insert the RC into the temporary table. IDENTITY_INSERT is OFF.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
stainer, 2022-02-11
@stainer

I found a crutch in Google, maybe it will come in handy for someone:

SELECT * INTO #temp_MarkaAutos_1644569816 FROM MarkaAutos WHERE 1<>1
UNION ALL
SELECT * FROM MarkaAutos where 1 = 0;

SET IDENTITY_INSERT MarkaAutos ON; --разрешаем вставку рк

INSERT INTO #temp_MarkaAutos_1644569816 (id,name,icon,slug,rusName) VALUES ('1','Acura','.jpg','acura','Акура');

MERGE INTO MarkaAutos AS t 
USING #temp_MarkaAutos_1644569816 AS t2 
ON 1=2
WHEN MATCHED THEN 
  UPDATE SET name = t2.name,icon = t2.icon,slug = t2.slug,rusName = t2.rusName 
WHEN NOT MATCHED THEN 
  INSERT (id,name,icon,slug,rusName) VALUES (t2.id,t2.name,t2.icon,t2.slug,t2.rusName);

SET IDENTITY_INSERT MarkaAutos OFF; --отключаем вставку рк

DROP TABLE #temp_MarkaAutos_1644569816; --удаляем временную таблицу

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question