需要动态检查一条记录,如果不存在则插入

Need to dynamically check for a record and insert if not exist

我想编写脚本来检查 table 中是否存在记录,如果不存在则插入。我想 运行 在不同的数据库中动态地使用它。

SELECT 1 from 
(SELECT parameter as parameter from @db_name.dbo.Table) a
WHERE parameter = 'new record'
if it doesn't retrieve a value
BEGIN 
INSERT

我试图使用动态 sql,但我卡住了。任何指导表示赞赏。

您可以通过 if exists

查看
IF NOT EXISTS (select 1 from dbo.Table WHERE parameter = 'new record')
  BEGIN
    -- INSERT
  End 
ELSE 
  BEGIN
    -- UPDATE
  END

但是如果你想在动态中做到这一点 sql :

declare @dbname varchar(100) 
        ,@sqlstring nvarchar(4000)
-- to avoid SQL injection you can do :
IF ( SELECT OBJECT_ID(@dbname+'.dbo.Table')) is not null 
   BEGIN
set @sqlstring = 'IF NOT EXISTS (select 1 from'+@dbname+'.dbo.Table WHERE parameter = ''new record'')
  BEGIN
    -- INSERT
  End 
ELSE 
  BEGIN
    -- UPDATE
  END'
END
EXEC sp_executesql @sqlstring